C語言程式設計 選擇排序簡介

來源:互聯網
上載者:User
選擇排序
選擇排序是通過每一趟排序過程中從待排序記錄中選擇出關鍵字最小(大)的記錄,將其依次放在資料表的最前或最後端的方法來實現整個資料表的有序排列。本節將介紹選擇排序方法中最簡單且最常用的簡單選擇排序。

選擇排序基本思想
  第一趟排序在所有待排序的n個記錄中選出關鍵字最小的記錄,將它與資料表中的第一個記錄交換位置,使關鍵字最小的記錄處於資料表的最前端;第二趟在剩下的n-1個記錄中再選出關鍵字最小的記錄,將其與資料表中的第二個記錄交換位置,使關鍵字次小的記錄處於資料表的第二個位置;重複這樣的操作,依次選出資料表中關鍵字第三小、第四小…的元素,將它們分別換到資料表的第三、第四…個位置上。排序共進行n-1趟,最終可實現資料表的升序排列。

/*
//===========================================
// 簡單選擇排序
// Author:Eman Lee
// Date: 10/21/2007
//===========================================
*/
#include<stdio.h>
#define N 10

void Display(int *a, int n)
{
    int i;
    for (i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
}

void SelectionSort(int *a, int n)
{
    int i, j, index, value;

    for (i = 0; i < n - 1; i ++) {
        index = i;
        value = a[i];
        for (j = i + 1; j < n; j ++)
            if (value > a[j]) {
                index = j;
                value = a[j];
            }
        a[index] = a[i];
        a[i] = value;
        Display(a, n);
    }
}

void main()
{
    int a[N],i ;
    for(i=0;i<N;i++)
        a[i]=N-i;
    Display(a, N);
    SelectionSort(a, N);
}

相關文章

聯繫我們

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