Simple selection sort (C++)

achieve

  1. Ideas
  • In a group of numbers to be sorted, choose the smallest (or largest) number to exchange with the number in the first position;
    then find the smallest (or largest) number and the number in the second position among the remaining numbers Exchange,
    and so on, until the n-1th element (the penultimate number) is compared with the nth element (the last number).
  1. Code
// 比a[i]小的最小元素下标
int select_min(int a[], int n, int i){
    
    
  int j = i;
  for (int k = i + 1; k < n; ++k) {
    
    
    if (a[j] > a[k]) {
    
    
      j = k;
    }
  }
  return j;
}

void select_sort(int a[], int n) {
    
    
  for (int i = 0; i < n; ++i) {
    
    
    int min = select_min(a, n, i);
    if (i != min) {
    
    
      int temp = a[i];
      a[i] = a[min];
      a[min] = temp;
    }
    
    // 测试用
    print(a, n, i + 1);
  }
}

test

  1. Code
#include <iostream>
using namespace std;

void print(int a[], int num, int index) {
    
    
  cout << " index = " << index << " : ";
  for (int i = 0; i < num; ++i) {
    
    
    cout << a[i] << " ";
  }
  cout << endl;
}

int main() {
    
    
  int a[] = {
    
    7, 6, 5, 4, 3, 2, 1};
  select_sort(a, sizeof(a) / sizeof(a[0]));
  cin.get();
  return 0;
}
  • result
 index = 1 : 1 6 5 4 3 2 7
 index = 2 : 1 2 5 4 3 6 7
 index = 3 : 1 2 3 4 5 6 7
 index = 4 : 1 2 3 4 5 6 7
 index = 5 : 1 2 3 4 5 6 7
 index = 6 : 1 2 3 4 5 6 7
 index = 7 : 1 2 3 4 5 6 7

Guess you like

Origin blog.csdn.net/luoshabugui/article/details/109390816