冒泡排序
从前往后(从后往前),两两比较,每趟比较可以确定一个元素的位置,时间复杂度为O(n^2),是一个稳定的排序。
#include <stdio.h>
#include <stdlib.h>
void Bubble_Sort(int k[],int n)//稳定的排序算法
{ int i,j;
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if(k[i]>k[j])
{
int temp=k[i];
k[i]=k[j];
k[j]=temp;
}
}
}
}
int main()
{
int a[]= {1,22,5,8,97,8,4,6,7};
Bubble_Sort(a,9);
int j;
for(j=0; j<9; j++)
{
printf("%d ",a[j]);
}
printf("Hello world!\n");
return 0;
}
改进的冒泡排序
#include <stdlib.h>
#include <stdio.h>
void Bubble_Sort(int k[],int n){
int i,j,temp,flag, count=0;
flag=1;
for(i=0;i<n-1&&flag;i++)
{ flag=0;
for(j=0; j<n-1; j++)
{
if(k[j+1]<k[j])//改进的冒泡排序,两两相比,若一次交换也没有,则原序列已有顺序。
{ count++;
temp=k[j+1];
k[j+1]=k[j];
k[j]=temp;
flag=1;
}
}
}
printf("%d ",count);//a[],17
}
int main()
{
int i,a[]={1,22,5,8,97,8,4,6,7};
int b[]={1,2,3,4,5,6,7,8,9};
Bubble_Sort(a,9);
printf("冒泡排序的结果是:");
for(i=0;i<9;i++){
printf("%d ",a[i]);
}
printf("\n\n");
return 0;
}
快速排序
一种基于分治的排序方式,(可以使用递归工作栈来实现)时间复杂度为O(nlogn),快速排序是不稳定的算法,快速排序是所有内部排序的算法中平均性能最优的排序算法。
#include <stdlib.h>
#include <stdio.h>
void swap(int k[],int a,int b)
{
int temp=k[a];
k[a]=k[b];
k[b]=temp;
}
int partition(int k[],int low,int high)//小于基准点的放左边,大于基准点的放右边,初始基准点为low
{
int point=k[low];//初始为第一个元素
while(low<high)
{
while(low<high&&point<=k[high])
{
high--;
}//执行结束后,point>high,交换位置
swap(k, low,high);
while(low<high&&point>=k[low])
{
low++;
}//执行结束后,point<low,交换位置
swap(k, low,high);
}//跳出while,low和high一样的
printf("high=%d,high=%d\n",low,high);
return low;
}
void QSort(int k[],int low,int high)
{
int privot;
if(low<high)
{
privot=partition(k, low, high);
QSort(k, low, privot-1);
QSort(k, privot+1, high);
}
}
void Quick_Sort(int k[],int n)
{
QSort(k,0,n-1);
}
int main()
{
int i,a[]= {1,22,5,8,97,8,4,6,7};
// int b[]= {1,2,3,4,5,6,7,8,9};
Quick_Sort(a,9);
printf("快速排序的结果是:");
for(i=0; i<9; i++)
{
printf("%d ",a[i]);
}
printf("\n\n");
return 0;
}