I have 2 different codes for sorting an array:
static void bubbleSort2(int[] arr){
System.out.println( "bubble starts ");
int tmp =0;int cnt =0;
for (int i=0; i< arr.length-1 ; i++){
for (int j=i+1; j< arr.length ; j++){
if(arr[i] > arr[j]){
tmp = arr[j];
arr[j]=arr[i];
arr[i] = tmp ;
}
cnt++;
}
printMe(arr);
}
System.out.println("Bubble cnt="+cnt);
printMe(arr);
}
And:
static void bubbleSort(int a[])
{
int len = a.length;
int cnt=0;
System.out.println( "bubble starts ");
for (int i = 0; i < len-1; i++){
for (int j = 0; j < len-i-1; j++) {
if (a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
cnt++;
}
printMe(a);
}
System.out.println("Bubble cnt="+cnt);
printMe(a);
}
bubbleSort2 is written by me, and I find it is printing the cnt value more than what the bubbleSort function is printing .
Below is the output for array --> int[] bbArr= { 28,6,4,2,24 };
bubbleSort(bbArr);
bubbleSort2(ccArr);
bubble starts
6,4,2,24,28
4,2,6,24,28
2,4,6,24,28
2,4,6,24,28
Bubble cnt=10
bubble starts
2,28,6,4,24
2,4,28,6,24
2,4,6,28,24
2,4,6,24,28
Bubble cnt=10
I see that one method keeps sorting from the starting position, while the other method keeps sorting from the last position of array. Does it really matter the order of sorting in a particular sorting algo?