筆試後,總結幾個排序

來源:互聯網
上載者:User

最近幾天去了好幾家公司的筆試,發現排序都會有,所以索性今天想把排序給整下,順便自己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~

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.