So I have tried to make this algorithm to work but everytime I run it I get [10,11,7,10,7,5,7,5 ] as my output. The goal was to get results in descending order. Furthermore I do not understand why there are 8 results when my array only contains 6 values. Please Help.. Thank you.
public class searches {
public static void main (String[]args)
{
int[] array = {10,7,11,5,13,8};
//ExchangeSort(array);
};
public static void ExchangeSort(int[] num)
{
int i,j,temp;
for(i=1;i<num.length-1;i++)
{
for(j=i+1;j<num.length;j++)
{
if(num[i]<num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
//System.out.println(temp);
}
}
}
};
};
You are ignoring first element in sorting as array index start from
0. Your first loop should start with index0and go up tolength-1as:Also you need to print the sorted array outside the loops or in the main method using
Arrays.toString(no loop required) as:and remove the semicolons
;from the end of the methods.Observatory Note: You method name shouldn’t start with Upper Case letter.
EDIT: Your full corrected code is as below: