Last active
December 17, 2015 23:39
-
-
Save agungsijawir/5691154 to your computer and use it in GitHub Desktop.
Sample QuickSort Implementation using C++
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
#include <iostream> | |
using namespace std; | |
void quickSort (int arr[], int kiri, int kanan) ; | |
int main() { | |
int isi = 0, loop = 0, arrSize = 0; | |
cout << "Program QuickSort sederhana\n"; | |
cout << "Berapa besar array? "; cin >> arrSize; | |
int larik[arrSize]; | |
// input array | |
cout << "Input angka (maks. " << arrSize << "): \n"; | |
do { | |
cin >> larik[isi]; | |
isi += 1; | |
} while (isi < arrSize); | |
quickSort (larik, 0, arrSize - 1); | |
// cetak hasil sortiran | |
while (loop < arrSize) { | |
cout << larik[loop] << " "; | |
loop += 1; | |
} | |
} | |
void quickSort (int arr[], int kiri, int kanan) { | |
int i = kiri, j = kanan, tmp; // init awal | |
int pivot = arr[(kiri + kanan) / 2]; // ambil nilai tengah | |
// partisi | |
while (i <= j) { | |
while (arr[i] < pivot) i++; | |
while (arr[j] > pivot) j--; | |
if (i <= j) { | |
tmp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = tmp; | |
i++; j--; | |
} | |
}; | |
// rekursi | |
if (kiri < j) quickSort (arr, kiri, j); | |
if (i < kanan) quickSort (arr, i, kanan); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment