DataStructors23
DataStructors23

Reputation: 137

Selection Sort not sorting in Java

I'm sorry if I am asking too many questions hopefully I will be able to help out on this site. I'm trying to create a selection sort, but no luck in the sorting aspect.

import java.util.Random;

public class Tester {
public static void main(String[] args) {
selectionSort(args);
}

private static void printArray(int[] anArray) {
    for (int i = 0; i < anArray.length; i++) {
       if (i > 0) {
          System.out.print(", ");
       }
       System.out.print(anArray[i]);
    }
 }

public static void selectionSort(String[] args) {

    int i,n = 0,x = 0;

    int l = 10;
    int temp;
    Random r = new Random();
    int array[] = new int[l];
    for(i = 0;i < l; i++){
        array[i] = r.nextInt(271);
    }

    printArray(array);
    while(n < l){

         for(int j=0; j<l; j++){
             if(array[j] < array[x])
                x = j;

        }
        temp = array[x];
        array[x] = array[n];
        array[n] = temp;
        n++;
        x = n;
     }
     printArray(array);
    }

}

I think most of my problems are coming from

     for(int j=0; j<l; j++){
         if(array[j] < array[x])
          x = j;

        }
        temp = array[x];
        array[x] = array[n];
        array[n] = temp;
        n++;
        x = n;
     }

I couldn't figure this bottom out. I can get the smallest digit sorted, but then it is in an odd order. I figured the x changed constantly and I needed to keep it in order so I had it equal n. After that not working I am at a loss. I appreciate the help.

Upvotes: 3

Views: 245

Answers (1)

TomN
TomN

Reputation: 584

You did the loop section incorrectly, so do this:

 for(int j=0; j<l; j++){
    if(array[j] < array[x])
        x = j;

 }

instead of this:

for(int j=x+1; j<l; j++)
    if(array[j] < array[x])
        x = j;

Notice that each loop of the selection sort should start from the next of last element which is done its part.

Upvotes: 5

Related Questions