21xrx.com
2024-09-19 23:53:38 Thursday
登录
文章检索 我的文章 写文章
C++简单选择排序代码
2023-07-13 03:49:50 深夜i     --     --
C++ 选择排序 简单 代码

选择排序是一种简单排序算法,其基本思想是找到列表中的最小值,并将其放在第一位,然后在剩余的列表中找到最小值并放在第二位,以此类推,直到整个列表排序完成。

以下是使用C++编写的简单选择排序代码:


#include <iostream>

using namespace std;

void selectionSort(int arr[], int n) {

  int i, j, minIndex, tmp;

  for (i = 0; i < n - 1; i++) {

    minIndex = i;

    for (j = i + 1; j < n; j++)

      if (arr[j] < arr[minIndex])

        minIndex = j;

    if (minIndex != i) {

      tmp = arr[i];

      arr[i] = arr[minIndex];

      arr[minIndex] = tmp;

    }

  }

}

void printArray(int arr[], int size) {

  int i;

  for (i=0; i < size; i++)

    cout << arr[i] << " ";

  cout << endl;

}

int main() {

  int arr[] = 80;

  int n = sizeof(arr)/sizeof(arr[0]);

  selectionSort(arr, n);

  cout << "Sorted array: \n";

  printArray(arr, n);

  return 0;

}

在这个代码中,我们定义了两个函数,一个用于选择排序(selectionSort)和另一个用于打印排序结果(printArray)。在排序函数中,我们使用了两个循环。外部循环向下遍历数组,内部循环在未排序的数组中查找最小值,并将其放入正确的位置。

在main()函数中,我们定义了一个未排序的整数数组,并计算出数组的大小。我们将该数组传递给排序函数,然后打印出排序后的数组。

在C++中,简单选择排序是一种非常有效的排序算法,并且它的实现非常简单。这个算法虽然不如其他高级排序算法那么快,但是仍然是一种非常常见的排序算法。在使用过程中,使用者可以根据具体的需要选择不同的排序算法来完成整个排序操作。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复