0

Why is this while loop not infinity in C?

I am learning a sorting algorithm called Quicksort. This is a simple sorting algorithm. I am following a tutorial in Youtube(Channel name: code with harry) The output of the code is absolutely correct. Problem explanation below: Inside the function called "partition", there is a while loop inside a do while loop. But that while loop does t have any terminating condition but still it outputs the correct result. Code snippet below: while (A[i] <= pivot) { i++; //A[]={9, 4, 4, 8, 7, 5, 6} //No terminating condition and works fine but how } Full code below: #include <stdio.h> void printArray(int *A, int n) { for (int i = 0; i < n; i++) { printf("%d ", A[i]); } printf("\n"); } int partition(int A[], int low, int high) { int pivot = A[low]; int i = low + 1; int j = high; int temp; do { while (A[i] <= pivot) { i++; //A[]={9, 4, 4, 8, 7, 5, 6} } while (A[j] > pivot) { j--; } if (i < j) { temp = A[i]; A[i] = A[j]; A[j] = temp; } } while (i < j); // Swap A[low] and A[j] temp = A[low]; A[low] = A[j]; A[j] = temp; return j; } void quickSort(int A[], int low, int high) { int partitionIndex; // Index of pivot after partition if (low < high) { partitionIndex = partition(A, low, high); quickSort(A, low, partitionIndex - 1); // sort left subarray quickSort(A, partitionIndex + 1, high); // sort right subarray } } int main() { int A[] = {9, 4, 4, 8, 7, 5, 6}; n =7; printArray(A, n); quickSort(A, 0, n - 1); printArray(A, n); return 0; }

8th Jun 2021, 9:17 AM
Sandesh Adhikari
Sandesh Adhikari - avatar
5 Respostas
+ 1
What makes you think so ? First while loop will break as soon as ( A[i] > pivot ) and other when ( A[j] <= pivot )
8th Jun 2021, 11:02 AM
Arsenic
Arsenic - avatar
+ 1
Arsenic okay but the pivot value is the largest value that is 9 and the comparison always returns true so i++ will keep executing or where I am wrong🤔 please explain
8th Jun 2021, 2:12 PM
Sandesh Adhikari
Sandesh Adhikari - avatar
+ 1
Sandesh Adhikari No wait, You are right 😅 The code have a UB. The loop will go on and will eventually attempt to acess elements beyond the its limit. Although it's pointless to explain UB but a possible explanation to why it might be working is because it may be eventually encountering a bigger value than that of `pivot` before accessing an illegal memory location and crashing to segmentation fault. This is happening more frequently because the array is living in stack (rather than on heap), making it less likely to encounter an illegal memory location.
8th Jun 2021, 5:14 PM
Arsenic
Arsenic - avatar
0
@Arsenic but what is UB in your answer??
9th Jun 2021, 9:53 AM
Sandesh Adhikari
Sandesh Adhikari - avatar
0
Thanks
10th Jun 2021, 2:26 PM
Sandesh Adhikari
Sandesh Adhikari - avatar