1. 冒泡排序:
void bubble_sort(int s[], int len)
{
int i,j,temp;
for (i=0;i<len;i++)
for(j=i;j<len;j++)
if(s[i] > s[j])
{
temp = s[i];s[i] = s[j]; s[j] = temp;
}
}
2. 插入排序:
void insert_sort(int s[], int len)
{
int i,j,temp;
for (i=1;i<len;i++)
{
temp = s[i];
for(j=i-1;j>=0 && s[j]>temp;j--)
s[j+1] = s[j];
s[j+1] = temp;
}
}
3.快速排序:
采用分治法,先选取一个数pivot,把小于pivot的数移到它的左边,大于pivot的数移到它的右边,然后进行递归调用
int partition(int s[],int low,int high)
{
int pivot = s[low];
while (low<high)
{
while (low<high && s[high]>=pivot)//必须加等号,处理相等的情况
high--;
s[low] = s[high];
while (low<high && s[low]<pivot)
low++;
s[high] = s[low];
}
s[low] = pivot;
return low;
}
void quick_sort(int s[], int low, int high)
{
int pos;
if (low<high)
{
pos = partition(s,low,high);
quick_sort(s,low,pos-1);
quick_sort(s,pos+1,high);
}
}
4.归并排序
也是采用分治法
void merge(int a[], int first, int mid, int last, int temp[])
{
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;
while (i <= m && j <= n)
{
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= m)
temp[k++] = a[i++];
while (j <= n)
temp[k++] = a[j++];
for (i = 0; i < k; i++)
a[first + i] = temp[i];
}
void merge_sort(int a[], int first, int last, int temp[])
{
if(first < last)
{
int mid = (first + last) / 2;
merge_sort(a, first, mid, temp);
merge_sort(a, mid + 1, last, temp);
merge(a, first, mid, last, temp);
}
}