一個無序自然數序列有N個自然數,快速找到二者之和為M的兩個整數並輸出。-小米電視

來源:互聯網
上載者:User

標籤:自然數   for   sort   排序   --   交換   void   bre   輸出   

思路:首先對無序自然數數列進行排序(升序),然後定義i和j分別指向數列的兩端,所指兩數之和分別和M作比較,比M大,則j左移,比M小,則i右移。

代碼如下:

#include <stdio.h>
#include <stdlib.h>

//快排
void sort(int *a, int left, int right)
{
    if(left >= right)
    {
        return ;
    }
    int i = left;
    int j = right;
    int key = a[left];

    while(i < j)                               /*控制在當組內尋找一遍*/
    {
        //雙向比較
        while(i < j && key <= a[j])
        {
            j--;                           //向前尋找
        }

        a[i] = a[j];                    //交換位置

        while(i < j && key >= a[i])
        {
            i++;                //向後尋找
        }

        a[j] = a[i];             //交換位置
    }

    a[i] = key;
    sort(a, left, i - 1);
    sort(a, i + 1, right);
}

int main()
{
    int a[10] = {-2,1,3,4,-5,12,45,34,23,9};
    int M = 26;
    int i, j;
    for(i = 0; i < 10; i++)
        printf("%d ",a[i]);
    printf("\n");
    sort(a, 0, 9);
    for(i = 0; i < 10; i++)
        printf("%d ",a[i]);
    printf("\n");
    i = 0;
    j = 9;
    while(i < j)
    {
        if(a[i] + a[j] == M)
            break;
        if(a[i] + a[j] > M)
            j--;
        else
            i++;
    }
    if(i != j)
        printf("%d + %d = %d\n",a[i],a[j],M);
    else
        printf("NO FIND!\n");
    return 0;
}

一個無序自然數序列有N個自然數,快速找到二者之和為M的兩個整數並輸出。-小米電視

聯繫我們

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