一、冒泡排序
相信冒泡排序大家都知道,无非是每一趟排序时将相邻两个元素进行交换,根据从大到小或从小到大的顺序,交换起来略有不同,如此进行n-1次排序即可得到整个数组有序。
1、平均时间复杂度为O(n^2)
2、最好情况下时间复杂度为O(n),此时设置标志位,元素有序时直接退出
3、最坏之间复杂度为O(n^2)
4、空间复杂度为O(1)
代码实现:
/*
*进行数组的冒泡排序
*/
#include<stdio.h>
#define MaxSize 100
/*
*进行冒泡排序
*/
void bubbleSort(int a[] , int length) ;
/*
*进行元素的交换
*/
void swap(int *a , int *b) ;
/*
*进行数组的显示
*/
void displayArray(int a[] , int length) ;
void main()
{
int a[MaxSize] , length , i ;
printf("Please input the length of the array : \n") ;
scanf("%d" , &length) ;
//进行数组元素的接收
for(i = 0 ; i < length ; i++)
{
scanf("%d" , &a[i]) ;
}
printf("Before sort... \n") ;
displayArray(a , length) ;
bubbleSort(a , length) ;
printf("After sort... \n") ;
displayArray(a , length) ;
}
void bubbleSort(int a[] , int length)
{
int i , j ;
int flag ;
flag = 1 ;
for(i = 0 ; i < length - 1 && flag ; i++)
{
for(j = 1 ; j < length - i ; j++)
{
flag = 0 ;
if(a[j] < a[j - 1])
{
swap(&a[j] , &a[j - 1]) ;
flag = 1 ;
}
}
}
}
void swap(int *a , int *b)
{
int temp ;
temp = *a ;
*a = *b;
*b = temp ;
}
void displayArray(int a[] , int length)
{
int i ;
for(i = 0 ; i < length ; i++)
{
printf("%4d" , a[i]) ;
}
printf("\n") ;
}
二、快速排序
快速排序即从数组中选择一个标志位,将比其小的元素放置在其前面,比其大的元素放置在其后面,然后将两边的前面的数组与后面的数组部分做同样的置换,直至元素有序即可。
1、平均时间复杂度为O(nlogn)
2、最好时间复杂度为O(nlogn)
3、最坏时间复杂度为O(n^2),此时元素基本有序
4、空间复杂度为O(logn)
代码实现
/*
*进行数组的快速排序
*/
#include<stdio.h>
#define MaxSize 100
/*
*快速排序算法
*/
void quickSort(int a[] , int low , int high) ;
/*
*进行一趟排序
*返回值为中间值的下标
*/
int quickPass(int a[] ,int low , int high) ;
/*
*进行数组的显示
*/
void displayArray(int a[] , int length) ;
void main()
{
int a[MaxSize] , length , i ;
printf("Please input the length of the array : \n") ;
scanf("%d" , &length) ;
//进行数组元素的接收
for(i = 0 ; i < length ; i++)
{
scanf("%d" , &a[i]) ;
}
printf("Before sort... \n") ;
displayArray(a , length) ;
quickSort(a , 0 , length - 1) ;
printf("After sort... \n") ;
displayArray(a , length) ;
}
void quickSort(int a[] , int low , int high)
{
int pass ;
if(low < high)
{
pass = quickPass(a , low , high) ;
quickSort(a , low , pass - 1) ;
quickSort(a , pass + 1 , high) ;
}
}
int quickPass(int a[] , int low , int high)
{
int temp ;
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 displayArray(int a[] , int length)
{
int i ;
for(i = 0 ; i < length ; i++)
{
printf("%4d " , a[i]) ;
}
printf("\n") ;
}