數字排序問題(c++實現)

來源:互聯網
上載者:User

標籤:

描述:給定n個整數,請統計出每個整數出現的次數,按出現次數從多到少的順序輸出。

輸入:輸入的第一行包含一個整數n,表示給定數位個數。
第二行包含n個整數,相鄰的整數之間用一個空格分隔,表示所給定的整數。

輸出:輸出多行,每行包含兩個整數,分別表示一個給定的整數和它出現的次數。按出現次數遞減的順序輸出。如果兩個整數出現的次數一樣多,則先輸出值較小的,然後輸出值較大的。

input:

125 2 3 3 1 3 4 2 5 2 3 5

output:

3 42 35 31 14 1

分析:該題痛點在於按出現次數遞減的順序輸出整數和他出現的次數,所以需要二維數組a[10][2],其中a[][0]存整數,a[][1]存該整數出現次數,排序時整體交換,如果出現相同則線輸出較小的再輸出較大的,這裡用到一個小技巧,具體看代碼。
 1 #include<iostream> 2 using namespace std; 3  4 void sort(int a[][2]) 5 { 6     int min; 7     int n = 0; 8     for (int i = 0; i < 10; i++)            //只對個數不為0的數字進行排序,由於初始是從小到大拍的,排序完成後相同的也是按從小到大 9     {10         if (a[i][1] != 0)11             n++;12     }13     for (int i = 0; i < n; i++)14     {15         for (int i = 0;; i++)16         {17             if (a[i][1] != 0)18             {19                 min = i;20                 break;21             }22         }23 24         for (int j = 0; j <= 9 - i; j++)25         {26             if (a[j][1]!=0)27                 if (a[min][1] >= a[j][1])28                     min = j;29         }30         int x = a[min][0], y = a[min][1];31         a[min][0] = a[9 - i][0]; a[min][1] = a[9 - i][1];32         a[9 - i][0] = x; a[9 - i][1] = y;33     }34 }35 int main()36 {37     int n,x;38     static int a[10][2];39     cin >> n;40     for (int i = 0; i < 10; i++)41         a[i][0] = i;42     for (int i = 0; i < n; i++)43     {44         cin >> x;45         a[x][1]++;46     }47     sort(a);48     for (int i = 0; i < 10; i++)49     {50         if (a[i][1] != 0)51             cout << a[i][0] << " " << a[i][1] << endl;52     }53     system("pause");54     return 0;55 }

PS:感覺寫麻煩了,歡迎有簡化方法的交流。。。。

數字排序問題(c++實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.