I have a small doubt while sorting arrays and yeah I am new to programming. Take a look at this code for example:
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
In the above code, why do we have to use j++
and i < (array.length-j)
as the test expression? We could have rather used i < (array.length)
as the test expression while omitting the variable j
. Any answers?
"Why do we have to use j++ and i < (array.length-j) as the test expression?"
The reason behind is at any time elements array[ array.length -j ]
to array[array.length - 1]
are already sorted.
Example: Say you have array of length n
.
So after the first iteration the biggest element will be placed at array[n - 1]
.
So because the largest element is already sorted on the next iteration we will only sort array of length n - 1
.
After the second iteration the second biggest element will be placed at array[ n - 2]
.
So because the 1st largest and 2nd largest elements are already sorted on the next iteration we will only sort array of length n - 2
, and so on...
The running time of the algorithm will be which is
As you said it we could have used i < (array.length - 1)
but we will be just doing a lot of work for nothing. If we do this the running time will be (n n) which is O(n n). But though the running time is still O(n*n) but it is obvious that is smaller than
, hence the first one is efficient.
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.