Wed Dec 19, 2012 5:20 pm
#include <iostream>
using namespace std;
void MergeSort(int* arrayPointer, int firstArrayLimit, int secondArrayLimit);
int main() {
int numbersArray[] = {23, 6, 4, 15, 664, 22, 18,50,2};
int arraySize = 9;
// Printing the array
cout<<" The Array Before Sorting:"<<endl;
for (int i = 0; i < arraySize; i++){
cout << numbersArray[i] << " ";
}
cout << endl;
// Merging Sort
for (int i = 1; i < arraySize; i *= 2) {
for (int j = 0; j < arraySize - i; j += 2*i) {
int subArrayToBeSortedSize = (2*i < arraySize - j) ? 2*i : arraySize - j;
MergeSort(&(numbersArray[j]), i, subArrayToBeSortedSize);
}
}
// Output sorted array
cout<<" The Array Sorted:"<<endl;
for (int i = 0; i < arraySize; i++){
cout << numbersArray[i] << " ";
}
cout << endl;
return 0;
}
void MergeSort(int* arrayPointer, int firstArrayLimit, int secondArrayLimit) {
int i = 0;
int j = firstArrayLimit;
int k = 0;
int* tempArray = new int[secondArrayLimit];
// Take each next smallest element
while (i < firstArrayLimit && j < secondArrayLimit) {
if (arrayPointer[i] < arrayPointer[j]) {
tempArray[k] = arrayPointer[i];
++i;
} else {
tempArray[k] = arrayPointer[j];
++j;
}
++k;
}
// Copy any remaining elements of the 1st array
while (i < firstArrayLimit) {
tempArray[k] = arrayPointer[i];
++i;
++k;
}
// Copy any remaining elements of the 2nd array
while (j < secondArrayLimit) {
tempArray[k] = arrayPointer[j];
++j;
++k;
}
// Copy the merged array back to the original
for (int iIndex = 0; iIndex < secondArrayLimit; ++iIndex) {
arrayPointer[iIndex] = tempArray[iIndex];
}
delete [] tempArray;
}
for (int i = 1; i < arraySize; i *= 2) {
for (int j = 0; j < arraySize - i; j += 2*i) {
int subArrayToBeSortedSize = (2*i < arraySize - j) ? 2*i : arraySize - j;
MergeSort(&(numbersArray[j]), i, subArrayToBeSortedSize);
}
}
while (i < firstArrayLimit && j < secondArrayLimit) {
if (arrayPointer[i] < arrayPointer[j]) {
tempArray[k] = arrayPointer[i];
++i;
} else {
tempArray[k] = arrayPointer[j];
++j;
}
++k;
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.