简体   繁体   中英

Why does my sorting algorithm fails after the 3rd iteration of the for loop?

/* This is the prompt:

starts with an unsorted array a

output: sorted array a.

Find the smallest element in the array a[1: n], call it a[j]. Swap it with a[0], if it is smaller than a[0]. Repeat this process with index 1, 2, ... until the who array is sorted. */

public class assing2 {

public static void main(String args[]) 
{ 
    //array of ints
    int[] A = new int[] {33, 20, 8, 11, 5};
    int min_id = 0;

    int temp_i = 0;
    //int temp_max = 0;


    for (int i = 0; i < A.length; i++) 
    {
        min_id = i;
        temp_i = A[i];

        for (int j = 1; j < A.length; j++)
        {
            if (A[min_id] > A[j])
            {
                min_id = j;

            }
        }


        A[i] = A[min_id];
        A[min_id] = temp_i;


    }

    System.out.println("Sorted array"); 
    for ( int i = 0; i < A.length; i++)
    {
        System.out.println(A[i]);
    }

} 

}

This is the output

Sorted array

5

20

11

33

8

When I run it in the debugger i can see that the first 2 iterations of the first for loop looks like its working but after that it unsorted what was sorted.

Whats is wrong with my logic?

for (int j = 1; j < A.length; j++) 

is wrong. You should check only the elements after i, since the elements before i are sorted by the previous iterations. So it should be

for(int j = i+1; j < A.length; j++) 

Also in the first loop, you dont need to do anything about the last element. You can change the stop condition to i<A.length-1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM