1,冒泡排序
void BubbleSort(int a[], int n)
{
int i, j, tmp;
int flag = 1;
for (i = 0; i < n && flag ; i++)
{
flag = 0;
for (j = 0; j < n - i - 1; j++)
if (a[j] > a[j+1])
{
tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
flag = 1;
}
}
}
2,选择排序
void SelectSort(int a[], int n)
{
int i, j;
int min, tmp;
for(i=0; i<n; i++)
{
min = i;
for(j=i+1; j<n; j++)
{
if (a[j]<a[min])
min = j;
}
if(min != i)
{
tmp = a[i];
a[i] = a[min];
a[min] = tmp;
}
}
}
3,插入排序
void InsertSort(int a[], int n)
{
int i, j;
int tmp;
for(i=1; i<n; i++)
{
tmp = a[i];
for (j=i-1; a[j]>tmp && j>=0; j--)
{
a[j+1] = a[j];
}
a[j+1] = tmp;
}
}
4,希尔排序
void ShellSort(int a[], int n)
{
int i, j, increment;
int temp;
for(increment = n/2; increment>0; increment/=2)
{
for(i=increment; i<n; i++)
{
temp = a[i];
for(j=i-increment; j>=0 && a[j]>temp; j=j-increment)
a[j+increment] = a[j];
a[j+increment] = temp;
}
}
}
5,快速排序
int Partition(int a[], int low, int high)
{
int temp = a[low];
while (low < high)
{
while (low<high && a[high]>=temp)
high--;
if (low < high)
{
a[low] = a[high];
low++;
}
while (low<high && a[low]<=temp)
low++;
if (low < high)
{
a[high] = a[low];
high--;
}
}
a[low] = temp;
return low;
}
void QuickSort(int a[], int low, int high)
{
int pivot;
if (low < high)
{
pivot = Partition(a, low, high);
QuickSort(a, low, pivot-1);
QuickSort(a, pivot+1, high);
}
}
6,归并排序
void Merge(int a[], int low, int mid, int high)
{
int i = low, j = mid+1;
int k = 0;
int *temp = (int*)malloc((high-low+1)*sizeof(int));
if (NULL == temp)
throw "Memory unavailable!";
while (i<=mid && j<=high)
{
if (a[i] < a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i<=mid)
temp[k++] = a[i++];
while (j<=high)
temp[k++] = a[j++];
for (i=low,k=0; i<=high; i++)
{
a[i] = temp[k++];
}
free(temp);
temp = NULL;
}
void MergeSort(int a[], int low, int high)
{
int mid;
if (low < high)
{
mid = low + (high-low)/2;
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
Merge(a, low, mid, high);
}
}
7,堆排序
void HeapAdjust(int a[], int s, int n)
{
int temp, i;
temp = a[s];
for (i=2*s+1; i<=n; i=i*2+1) //这里因为大顶堆下标是从0开始,所以求左孩子节点为2*s+1
{
if (i<n && a[i+1] > a[i])
i++;
if (a[i] > temp)
{
a[s] = a[i];
s = i;
}
else
break;
}
a[s] = temp;
}
void HeapSort(int a[], int n)
{
int i, temp;
for (i=n/2; i>=0; i--)
HeapAdjust(a, i, n-1);
for (i=n-1; i>0; i--)
{
temp = a[0];
a[0] = a[i];
a[i] = temp;
HeapAdjust(a, 0, i-1);
}
}
时间复杂度和空间复杂度总结