Here is my homework: I want to know how many compares and exchanges take place in selection sort. When I declared my array in reverse or in descending order like this:
int arr[] = { 5, 4, 3, 2, 1 };
…it's running fine and count compares and exchanges too but when I try to give 'n' and filled array in reverse order, it filled it in descending order but it didn't work properly to sort in descending order to count my exchanges although it count compares.
Here is the code:
public class SelectionSort {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
int compares = 0, exchanges = 0, x;
x = in.nextInt();
int[] arr = new int [x];
int n = arr.length;
int s = 0;
int min;
int temp, i, j;
System.out.print("Filling Array");
for(i = n - 1; i > 0; i--)
{
arr[i] = i;
System.out.print(" " + arr[i]);
}
System.out.println("");
for(i = 0; i < n ; i++)
{
min = i ;
for(j = i + 1; j < n; j++)
{
compares++;
if(arr[min] > arr[j])
min = j;
}
if(min != i)
{
exchanges++;
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
System.out.println("Iteration " + (++s));
for(int a = 0; a < arr.length; a++)
System.out.print(" " + arr[a]);
System.out.println("");
}
System.out.println("");
System.out.println("Compares -- >> " + compares);
System.out.println("Exchanges -->> " + exchanges);
}
}
There is a very simple reason for this to show the wrong count of EXCHANGES
that take place. If you follow the code here:
System.out.print("Filling Array");
for(i = n - 1; i > 0; i--)
{
arr[i] = i;
System.out.print(" " + arr[i]);
}
Got it yet? The array is never filled or sorted in descending order, you are only printing it in reversed order.
Let's suppose n = 3
and when the array is initialized it's { 0, 0, ... }
and follow the loop:
Iteration 1:
// i = n - 1 = 2
// i > 0 = true
// arr[i] = i;
// arr[2] = 2;
// print statement
Iteration 2:
// i - 1 = 1
// i > 0 = true
// arr[i] = i;
// arr[1] = 1;
// print statement
Iteration 3:
// i - 1 = 0
// i > 0 = false
// arr = { 0, 1, 2 }
Try this for a filling a reverse sorted array:
for (i = n - 1, z = 0; i > 0; i--, z++)
{
arr[z] = i;
}