最近幾天去了好幾家公司的筆試,發現排序都會有,所以索性今天想把排序給整下,順便自己vs6.0裡調了下。
今天晚上總結了兩個排序
1)選擇排序:每輪找到最大或最小的放在頂部
2)冒泡排序:每輪找到最大或最小的沉到底部
選擇排序代碼:
void selectionSort(int arr[],int n)//選擇排序
{
int smallIndex;
int pass, j;
int temp;
for(pass=0;pass<n-1;pass++)
{
smallIndex=pass;
for(j=pass+1;j<n;j++)
if(arr[j]<arr[smallIndex])
smallIndex = j;
if(smallIndex !=pass)
{
temp=arr[pass];
arr[pass]=arr[smallIndex];
arr[smallIndex]=temp;
}
}
}
冒泡排序代碼:
void bubbleSort(int arr[], int n)//冒泡排序
{
int bigIndex;
int pass, j;
int temp;
for(pass=n-1;pass>0;pass--)
{
bigIndex=pass;
for(j=0;j<=pass;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
測試代碼:
void main()
{
int arr[15];
int i;
cout<<"Original array"<<endl;
for(i=0;i<15;i++)
{
arr[i]=rand();
cout<<arr[i]<<" ";
}
cout<<endl<<endl;
// selectionSort(arr,15);
bubbleSort(arr,15);
cout<<"Sorted array" <<endl;
for(i=0;i<15;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
接下來的幾個排序明天再搞上去,先休息下,O(∩_∩)O~