在春天午后,阳光和煦,写一篇博客,来舒缓心情,技术积累不是一朝一夕的事,加油吧,每个不甘平庸得你。写个冒泡排序和快速排序。
冒泡排序
#incuede<iostream>
#inclued<stdio.h>
using namespace std
void BubbleSort(int array[],int len)
{
if(len ! = 0)
{
for(int i = 0; i<len;i++)
{
for(int j = i + 1;j<len;j++)
{
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
}
void Print(int array[],int len)
{
for(int i = 0;i<len;i++)
{
cout << array[i] << endl;
}
}
void QuickSort(int array[];int left;int right)
{
int i = left;
int j = right;
int x= array[left];
if(i < j)
{
while(i<j)
{
while(i<j && array[j] > x)
{
j--;
}
if(i<j)
{
s[i++] = s[j];
}
while(i<j && array[i] < x)
{
i++;
}
if(i<j)
{
s[j--] = s[i];
}
}
array[i] = x;
QuickSort(array,left,i-1);
QuickSort(array,i+1,right);
}
}
void main()
{
int array[] = {1,9,3,6,2,7,4};
int len = 7;
cout << "排序前:" << endl;
Print(array,len);
cout<<"排序后"<< endl;
BubbleSort(array,len);
Print(array,len);
cin.get();//控制台不闪退
cout<<"Hello world"<<endl;
}
快速排序:选一个基准,上面选择array[left];第一遍选择从右向左遍历,找到第一个比基准小得数,交换位置;然后从左向右遍历,找到第一个比基准大得数,交换位置;以此规则遍历,得最后结果。快速排序得平均复杂度是Olg(n);冒泡排序平均复杂度O(n*n);代码为纯手打,为锻炼手写能力,有错难免,请包含。