#include <iostream>
#include <vector>
using namespace std;
void mswap(int &a, int &b)
{
int c = a;
a = b;
b = c;
}
void print(int *a, int size)
{
for (int i = 0; i<size ; i++)
{
cout<<a[i]<<" ";
}
}
//Start at the beginning of an array and swap the first two elements if the first is bigger than
// the second Go to the next pair, etc, continuously making sweeps of the array until sorted
// O(n^2)
void bubbleSort(int *a, int size)
{
if (a == NULL || size<0)
{
return;
}
for (int j = 0; j <size ; j ++)
{
for (int i = 0; i< size-1-j; i++)
{
if (a[i] > a[i+1])
{
mswap(a[i], a[i+1]);
}
}
}
}
//Find the smallest element using a linear scan and move it to the front Then, find the second
// smallest and move it, again doing a linear scan Continue doing this until all the elements
// are in place O(n^2)
void selectSort(int *a, int size)
{
if (a == NULL || size<0)
{
return;
}
for (int i = 0; i<size ;i ++)
{
int k = i;
for (int j = i; j<size; j++)
{
if (a[k] > a[j])
{
k = j;
}
}
swap(a[k],a[i]);
}
}
//Sort each pair of elements Then, sort every four elements by merging every two pairs Then,
//sort every 8 elements, etc O(n log n) expected and worst case
void mSort(int *a, int begin, int end, int* temp)
{
if (a == NULL)
{
return;
}
int mid = (begin + end)/2;
int i = begin;
int j = mid+1;
int p = 0;
while (i<=mid && j<=end)
{
if (a[i]>a[j])
{
temp[p] = a[j];
p++;
j++;
}
else
{
temp[p] = a[i];
p++;
i++;
}
}
while(i<=mid)
{
temp[p] = a[i];
p++;
i++;
}
while(j<=end)
{
temp[p] = a[j];
p++;
j++;
}
for (i = 0; i < p; i++)
a[begin + i] = temp[i];
}
void merge(int *a, int begin, int end, int *temp)
{
if (begin<end)
{
int mid = (begin + end)/2;
merge(a,begin,mid,temp);
merge(a,mid +1,end,temp);
mSort(a,begin,end,temp);
}
}
//Quick Sort
//Pick a random element and partition the array, such that all numbers that are less than it
// come before all elements that are greater than it Then do that for each half, then each
//quarter etc O(n log n) expected, O(n^2) worst case.
int partion(int *a, int begin, int end)
{
int t = a[begin];
int low = begin;
int high = end;
while(low < high)
{
while(low < high&& t<=a[high])
{
high--;
}
mswap(a[low],a[high]);
while(low < high && t>=a[low])
{
low++;
}
mswap(a[low],a[high]);
}
return low;
}
void quickSort(int *a, int begin, int end)
{
if (begin < end)
{
int i = partion(a, begin, end);
quickSort(a, begin, i-1);
quickSort(a, i + 1, end);
}
}
int main()
{
int a[] = {78, 17, 39, 26, 72, 94, 21, 12, 23, 91};
//bubbleSort(a,6);
//selectSort(a,6);
// int *p = new int[6];
// merge(a,0,5,p);
// quickSort(a,0,5);
print(a,10);
return 0;
}
Cracking The Coding Interview 9.0
最新推荐文章于 2017-03-29 21:16:03 发布