Last active
May 3, 2022 13:53
-
-
Save yadav26/2f92cec00153b29909213f77e695fc13 to your computer and use it in GitHub Desktop.
QuickSort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// QkCTest.cpp : This file contains the 'main' function. Program execution begins and ends there. | |
// | |
//#include "pch.h" | |
#include <iostream> | |
using namespace std; | |
int myArray[] = { 21,10,5,2,21,19,6,9, 11, 17, 11, 8, 8, 8,12,0,0,0,0,19,21,21 }; | |
const int glen = sizeof(myArray) / sizeof(int); | |
void Swap(int i, int j) | |
{ | |
int t = myArray[j]; | |
myArray[j] = myArray[i]; | |
myArray[i] = t; | |
return; | |
} | |
void printArray() | |
{ | |
cout << "\nPrintArray - "; | |
for (int i = 0; i < glen; ++i) | |
{ | |
cout << myArray[i] << " "; | |
} | |
return; | |
} | |
void Partition( int start, int end ) | |
{ | |
int i = start + 1; | |
int j = end; | |
if (end <= start) | |
return; | |
cout << "\n\nPartition Enter : " << start << " := " << myArray[start] << ", " << j << ":= " << myArray[j]; | |
int pivot = myArray[start]; | |
cout << "\nPivot => " << start << ":= " << myArray[start]; | |
//printArray(); | |
if (start + 1 == j) // To Fix - why last two elements not exchanging using normal recursion; special case applied. | |
{ | |
if (myArray[start] > myArray[j]) | |
Swap(start, j); | |
return; | |
} | |
while (i < j) | |
{ | |
while (pivot >= myArray[i] && i < glen-1) | |
++i;//move i forward till element is lesser then pivot | |
while (pivot < myArray[j] && j > 0) | |
--j; // move j backward till element is greater then pivot | |
//cout << "\nSwaping :j = a[ " << j << " ]=" << myArray[j] << ",start = a[ " << start << "]= " << myArray[start]; | |
if (i < j) // swap the elements | |
{ | |
Swap(i, j); | |
} | |
else | |
{ | |
//cout << "\nPivot loc found " << j ; | |
Swap(start, j); | |
} | |
} //repeat | |
printArray(); | |
Partition( start, j-1 ); | |
Partition( i, end); | |
} | |
void QuickSort( ) | |
{ | |
Partition( 0, glen-1 ); | |
return; | |
} | |
int main() | |
{ | |
std::cout << "Hello Quick World!\n"; | |
QuickSort(); | |
std::cout << "Final Result - \n"; | |
printArray(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment