Why is this while loop not infinity in C? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
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
5 ответов
+ 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
+ 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