zoukankan      html  css  js  c++  java
  • 选择排序

    选择排序工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。这里依旧分别列出C、OC和swift版本的代码,欢迎交流、指正。

    C语言版

    //函数声明
    void select_sort(int a[], int n);

    int array[11] = {23890127, -95433699, -17};
    //调用
    select_sort(array, 11);
    printf("sort result:");
    for (int p = 0; p < 11; p++) {
        printf(" %d", array[p]);
    }
    printf(" ");
    //sort result: -17 -9 3 7 8 12 23 36 54 90 99

    void select_sort(int a[], int n) {
        int min = 0;
        //每次找到第(i+1)小的数 从左到右依次排列
        for (int i = 0; i < n-1; i++) {
            min = i;
            //找到第(i+1)小的数的下标
            for (int j = i+1; j < n; j++) {
                if (a[j] < a[min]) {
                    min = j;
                }
            }
            
            int temp = a[i];
            a[i]     = a[min];
            a[min]   = temp;
        }
    }

    OC版

    _dataArray = [NSMutableArray arrayWithObjects:@21, @3, @34, @(-28), @10, @(-33), @54, @9, @0, @(-2),  nil];

    [self selectSort];
    NSString *string = [self.dataArray componentsJoinedByString:@" "];
    NSLog(@"sort result : %@"string);
    //sort result : -33 -28 -2 0 3 9 10 21 34 54

    - (void)selectSort {
        NSInteger minIndex = 0;
        for (int i = 0; i < self.dataArray.count-1; i++) {
            minIndex = i;
            for (int j = i+1; j < self.dataArray.count; j++) {
                if ([self.dataArray[j] integerValue] < [self.dataArray[minIndex] integerValue]) {
                    minIndex = j;
                }
            }
            
            [self.dataArray exchangeObjectAtIndex:i withObjectAtIndex:minIndex];
        }
    }

    swift版

    var dataArray:NSMutableArray = [76119, -424680, -19];

    self.selectSort();
    let string:NSString = dataArray.componentsJoinedByString(" ");
    NSLog("sort result: %@"string);
    //sort result: -19 -4 0 1 2 4 6 8 19 76

    func selectSort() {
        var minIndex:NSInteger = 0;
        
        for i:NSInteger in 0..<dataArray.count-1 {
            minIndex = i;
            for j:NSInteger in i+1..<dataArray.count {
                if dataArray[j].integerValue < dataArray[minIndex].integerValue {
                    minIndex = j;
                }
            }
            
            dataArray.exchangeObjectAtIndex(i, withObjectAtIndex:minIndex);
        }
    }

  • 相关阅读:
    今天面试一些程序员(新,老)手的体会
    UVA 10635 Prince and Princess
    poj 2240 Arbitrage
    poj 2253 Frogger
    poj 2485 Highways
    UVA 11258 String Partition
    UVA 11151 Longest Palindrome
    poj 1125 Stockbroker Grapevine
    poj 1789 Truck History
    poj 3259 Wormholes
  • 原文地址:https://www.cnblogs.com/NINIiOS/p/5664249.html
Copyright © 2011-2022 走看看