1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <iostream>
using namespace std;
int* fungsi(int* ptr, int arraySize){
int* leftSortedArray = NULL;
int* rightSortedArray = NULL;
int halfSize = arraySize / 2;
if(arraySize > 1){
int* tempLeft = new int[halfSize];
int* tempRight = new int[arraySize - halfSize];
int leftIndex = 0, rightIndex = 0;
int i = 0;
for(; i < halfSize; i++) tempLeft[i] = ptr[i];
for(int a = 0; i < arraySize; i++) tempRight[a++] = ptr[i];
leftSortedArray = fungsi(tempLeft, halfSize);
rightSortedArray = fungsi(tempRight, arraySize - halfSize);
for(int i = 0; i < arraySize; i++){
if((leftIndex == halfSize) || (rightIndex == arraySize - halfSize)){
if(leftIndex == halfSize) ptr[i] = rightSortedArray[rightIndex++];
else ptr[i] = leftSortedArray[leftIndex++];
}
else{
if(leftSortedArray[leftIndex] < rightSortedArray[rightIndex]) ptr[i] = leftSortedArray[leftIndex++];
else ptr[i] = rightSortedArray[rightIndex++];
}
}
delete[] tempLeft;
delete[] tempRight;
}
return ptr;
}
int main(){
int array_of_int[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int* sortedArray = fungsi(array_of_int, 11);
for(int i = 0; i < 10; i++){
cout << sortedArray[i] << " ";
}
return 0;
}
|