Results 1 to 2 of 2

Thread: selection sort

  1. #1
    mayhewj7 is offline Member
    Join Date
    Dec 2008
    Posts
    39
    Rep Power
    0

    Default selection sort

    I have to create a random array of ints[]. Then I have to sort the array of ints using a selection sort. I cant seem to figure out what im doing wrong with my code. If anyone could help I would greatly appreciate it. Thanks

    import java.util.*;
    import java.io.*;

    public class RandomInts
    {
    private static final int SIZE = 10;
    Random ran = new Random();
    int[] a = new int[SIZE];

    public void random(){
    for(int i = 1; i < a.length; i++){
    a[i]= (int)(Math.random() * 100);
    System.out.println(a[i]);
    }
    System.out.println("\n");
    }

    public void selectionSort() {
    for (int i=0; i<a.length-1; i++) {
    int min = i;
    for (int j=i+1; j<a.length; j++) {
    if (a[min] > a[j]) {
    min = j;
    }
    }
    if (min != i) {
    int temp = a[i];
    a[i] = a[min];
    a[min] = temp;
    System.out.println(a[min]);
    }
    }
    }


    public static void main(String[] args){
    RandomInts b = new RandomInts();
    b.random();
    b.selectionSort();
    }


    }



    That is the code I have so far and this is what it prints out:

    30
    54
    50
    83
    28
    20
    23
    59
    91


    30
    54
    50
    83
    83
    83



    It needs to print from largest to smallest smallest to largest.

    thanks

  2. #2
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    12

    Default

    nothing is wrong, you need to print the output in main() NOT inside the sorting loop.
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

Similar Threads

  1. Using Merge Sort to sort an ArrayList of Strings
    By coldfire in forum New To Java
    Replies: 3
    Last Post: 03-13-2009, 01:03 AM
  2. Replies: 3
    Last Post: 01-26-2009, 12:20 AM
  3. write a selection sort without having numerous variable?
    By seandingobat in forum New To Java
    Replies: 6
    Last Post: 10-28-2008, 02:33 PM
  4. How to sort a list using Bubble sort algorithm
    By Java Tip in forum Algorithms
    Replies: 3
    Last Post: 04-29-2008, 08:04 PM
  5. Selection sort in Java
    By Java Tip in forum Algorithms
    Replies: 0
    Last Post: 04-15-2008, 07:41 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •