ACM——直接插入法排序

NOJ——1062

直接插入排序

時間限制(普通/Java):1000MS/3000MS          運行內存限制:65536KByte
總提交:446            測試經過:212ios

描述算法

給定輸入排序元素數目n和相應的n個元素,寫出程序,利用內排序算法中直接插入排序算法進行排序,並輸出排序過程當中每趟及最後結果的相應序列。數據結構

輸入測試

共兩行,第一行給出排序元素數目n,第二行給出n個元素,1n400,每一個元素值範圍爲 [0100000)spa

輸出code

三個部分:

第1部分爲兩行,第1行輸出文字「Source:」,第2行給出原始序列;

第2部分,開始輸出文字「Insert Sort:」,後續輸出簡單選擇排序過程;

第3部分,開始輸出文字「Result:」,後續輸出排序結果。blog

樣例輸入排序

7
48 36 68 72 12 48 2
內存

樣例輸出io

Source:
(48) 36 68 72 12 48 2
Insert Sort:
(36 48) 68 72 12 48 2
(36 48 68) 72 12 48 2
(36 48 68 72) 12 48 2
(12 36 48 68 72) 48 2
(12 36 48 48 68 72) 2
(2 12 36 48 48 68 72)
Result:
(2 12 36 48 48 68 72)

提示

 數據結構A實驗四

題目來源

CHENZ

 

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    int N,i,j;
    scanf("%d",&N);
    int* p=new int[N];
    for(i=0;i<N;i++)
        scanf("%d",&p[i]);
    printf("Source:\n(%d)",p[0]);
    for(i=1;i<N;i++)
    printf(" %d",p[i]);
    printf("\nInsert Sort:\n");
    for(i=1;i<N;i++){
        if(p[i]<p[i-1])
        {
        int temp=p[i];
        for(j=i-1;j>=0&&temp<p[j];j--){
        p[j+1]=p[j];
        }
        p[j+1]=temp;
        }
        printf("(%d",p[0]);
        for(int t=1;t<=i;t++) printf(" %d",p[t]);
        printf(")");
        for(int t=i+1;t<N;t++) printf(" %d",p[t]);
        printf("\n");
    }
    printf("Result:\n(%d",p[0]);
    for(i=1;i<N;i++)
    printf(" %d",p[i]);
    printf(")\n");    
    return 0;
}

 

相關文章
相關標籤/搜索