#include<string.h>
#include<stdio.h>
#include<iostream>
using namespace std;
#define MAX_LENGTH 10
void quickSort(int* a, int low, int high)
{
if (low >= high || NULL == a)
{
return;
}
int i = low;
int j = high;
int tempKey = a[i];
if (i < j)
{
while(i < j)
{
while(i < j && tempKey <= a[j])
{
j--;
}
if(i < j && tempKey > a[j])
{
a[i] = a[j];
i++;
}
while(i < j && tempKey >= a[i])
{
i++;
}
if(i < j && tempKey < a[i])
{
a[j] = a[i];
j--;
}
}
if(i == j)
{
a[i] = tempKey;
}
}
if(low < i-1)
{
quickSort(a, low, i-1);
}
if(i+1 < high)
{
quickSort(a, i+1, high);
}
}
void insertSort(int a[], int length)
{
if(NULL == a || length <= 0)
{
return;
}
for (int i = 1; i < length; i++)
{
for (int j = i - 1; j >= 0 && a[j] > a[j + 1]; j -= 1)
{
swap(a[j], a[j + 1]);
}
}
}
void shellSort(int a[], int length)
{
if(NULL == a || length <= 0)
{
return;
}
for (int gap = length / 2; gap > 0; gap /= 2)
{
for (int i = gap; i < length; i++)
{
for (int j = i - gap; j >= 0 && a[j] > a[j + gap]; j -= gap)
{
swap(a[j], a[j + gap]);
}
}
}
}
void selectSort(int* a, int length)
{
if(NULL == a || length <= 0)
{
return;
}
for(int i = 0; i < length; i++)
{
int tempIndex = i;
bool bchange = false;
for(int j = i + 1; j < length; j++)
{
if(a[tempIndex] > a[j])
{
tempIndex = j;
bchange = true;
}
}
if(bchange == true)
{
swap(a[i], a[tempIndex]);
}
}
}
void bubbleSort(int* a, int length)
{
if(NULL == a || length <= 0)
{
return;
}
bool bchange = false;
for(int i = 0; i < length - 1; i++)
{
for(int j = length -1; j > i; j--)
{
if(a[j] < a[j-1])
{
swap(a[j], a[j-1]);
bchange = true;
}
}
if(!bchange)
{
return;
}
}
}
int main()
{
int a[MAX_LENGTH] = {30, 10, 29, 39, 18, 90, 0, 58, 29, 4};
int length = sizeof(a)/sizeof(int);
cout << "length=" << length <<endl;
bubbleSort(a, length);
for(int i = 0; i < length && i < MAX_LENGTH; i++)
{
cout << a[i] << " ";
}
system("pause");
return 0;
}