Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
#include <iostream>
#include <iomanip> //needed for the sset field width() std::setw
using namespace std;
#define SIZE 5 //we need to define the size of the array
void swap(int list[], int a, int b) //a swap function for a and b pointers, left and right pointers
{
//temporary variable to hold the passing values
int tempo;
tempo = list[a];
list[a] = list[b];
list[b] = tempo;
}
//print function
void print(const int arr[])
{
//loops through the array and prints
for(int x=0;x < SIZE; x++) {
cout << setw(3) << arr[x];
}
cout << endl;
}
//the actual function for the quick sort
void quick_sort(int list[], int left_extreme, int right_extreme)
{
int left, right, pivot;
if(left_extreme >= right_extreme){ //if th
return;
}
//created new variables and gave them the values of both extremes (left and right)
left = left_extreme;
right = right_extreme;
//the pivot is the addition of both left and right divided by 2
//this is how we find the middle pivot
pivot = list[(left_extreme + right_extreme) /2];
// partition
while(left <= right) {
while(list[left] < pivot) left++;
while(list[right] > pivot) right--;
if(left <= right) {
swap(list,left,right);
left++; right--;
}
//we make a printing of the list
print(list);
}
// call the function again to keep scaning
quick_sort(list,left_extreme,right);
quick_sort(list,left,right_extreme);
}
int main()
{
int list[SIZE]={3,5,2,1,4}; //the list has to contain 5 elements, as the size was defined
print(list); //the function will print the list
quick_sort(list,0,SIZE-1); //the last function is the actual quick sort algorithm
}