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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
//
// main.cpp
// exercise 8.15
//
// Created by James Farrow on 11/02/2016.
// Copyright © 2016 James Farrow. All rights reserved.
//
// quicksort algorithm
#include <iostream>
#include <ctime>
int partition( int[], int, int);
void quickSort(int[], int, int);
int main()
{
srand ( static_cast<unsigned int>( time ( NULL )));
const int arraySize = 12;// const variable for arraysize
const int arrayStart = 0;
int randomArray[] = {13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11};//initilaise array with zero
//int randomArray[arraySize] = { 0 };//initilaise array with zero
//fill array with random numbers to sort
//for (int i = 0; i < arraySize; i++) {
//randomArray[i] = 1 + rand() % 100;
//}
//print array to screen
for (int i = 0; i < arraySize; i++) {
std::cout << randomArray[i] << " ";
}
//int pivot = 0;
//pivot = partition(randomArray,arrayStart, arraySize);
quickSort(randomArray, arrayStart, arraySize);
//std::cout << "pivot: " << pivot << std::endl;
std::cout << std::endl;
//print array to screen
for (int i = 0; i < arraySize; i++) {
std::cout << randomArray[i] << " ";
}
std::cout << std::endl;
}
int partition(int array[],int start, int end)
{
int x = array[end - 1];
int i = -1;
for (int j = start; j < end - 1 ; j++) {
if (array[j] <= x) {
i++;
std::swap(array[i],array[j]);
}
}
std::swap(array[i + 1], array[end - 1]);
return i+1;
}
void quickSort(int array[], int start, int end)
{
int q = 0;
if (start < end) {
q = partition(array, start, end);
quickSort(array, start, q - 1);
quickSort(array, q + 1, end - 1);
}
}
|