C語言基礎總結 ( 二 )----------數組總結( 重點排序演算法 )

來源:互聯網
上載者:User

標籤:

??寫一個程式,初始化一個數組。要求數組長度為10,裡面的值為0-9的隨機數,並且每一個數字出現一次。思路: 1,建立數組 2,建立隨機數
 3,存到數組中 nums[i++] = ...
 4,使用迴圈建立資料,並加入到數組中.迴圈幾次? while(i < 10)
 5,建立數字,判斷數組中是否有該數字,如果沒有就加入,如果有就重新建立
 6,如何判斷一個數字在數組中或不在數組中呢?
 int nums[] = {1,2,3};
 3在不在,4在不在?
 遍曆一下,看直到遍曆結束,如果都沒有這個數字,就表示不存在 數組初始化?  用代碼來實現:  int nums[LEN], i = 0, temp, index;
    while (i < 10) {
        temp = arc4random_uniform(10);
        // 迴圈用隨機數和數組元素比較,看是否相等
        for (index = 0; index < i; index++) {
            if (temp == nums[index]) {
                break;
            }
        }
        // index == i說明for迴圈結束,隨機數和數組元素不相等
        if (index ==  i) {
            nums[i++] = temp;
        }
    }
    // 迴圈結束,把隨機數列印出來
    for (int j = 0; j < 10; j++) {
        printf("%d\t%d\n", j + 1, nums[j]);    }   ??冒泡排序void bubbleSort(int nums[], int lengh){
    for (int i = 0; i < lengh - 1; i++) {
        for (int j = 0; j < lengh - 1 - i; j++) {
            if (nums[j] > nums[j + 1]) {
                int temp = nums[j];
                nums[j] = nums[j + 1];
                nums[j + 1] = temp;
            }
        }
    }
} ??選擇排序void chooseSort(int nums[], int length){
    for (int i = 0; i < length - 1; i++) {
        for (int j = i; j < length; j++) {
            if (nums[j] < nums[i]) {
                int temp = nums[j];
                nums[j] = nums[i];
                nums[i] = temp;
            }
        }
    }
} ??選擇排序最佳化:int min = -1;
    for(int j = 0; j < 4 - 1; j++) {
        min = j; // 記錄了最小取值的下標(索引)
        for (int i = j + 1; i < 4; i++) {
            if(nums[min] > nums[i]) {
                min = i;
            }
        }
       
        // 將最小的與第j項交換
        if(min != j) {
            temp = nums[min];
            nums[min] = nums[j];
            nums[j] = temp;
        }    }  ??二分法尋找資料  前提:數組是從小到大排列的// 二分法就是折中來求,目標資料大於中間數,就在右半邊中找,迴圈執行...
// 假定找到目標資料,就返回它的下標,如果沒找到,就返回-1
int indexOf(int nums[], int length, int keydata){   // keydata 表示要找的目標資料
// 由於要執行迴圈的次數未知,所以用while迴圈來實現
    int low = 0, high = length - 1,mid;
    while (low <= high) {
        mid = (low + high) / 2;
        if (keydata == nums[mid]) {
            return mid;
        }else if (keydata > nums[mid]){
            low = mid + 1;
        }else high = mid - 1;
    }
    return -1;} 

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.