3

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I don't have 15 reputation, please rate up TomN up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.