数据结构各种排序算法实现代码
时间: 2024-06-15 07:01:35 浏览: 13
数据结构中的排序算法是计算机科学的基础,它们用于对一组元素按照特定规则进行有序排列。这里列举几种常见的排序算法以及它们的基本实现(使用伪代码表示):
1. **冒泡排序**:
```plaintext
for i = 0 to length-1 do
for j = 0 to length-i-1 do
if arr[j] > arr[j+1] then
swap(arr[j], arr[j+1])
```
相关问题
数据结构冒泡排序算法的代码
好的,以下是冒泡排序算法的代码(C++实现):
```
void bubbleSort(int arr[], int n){
for (int i = 0; i < n - 1; i++){
for (int j = 0; j < n - i - 1; j++){
if (arr[j] > arr[j + 1]){
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
其中,`arr`是待排序的数组,`n`是数组的长度。外层循环控制排序的轮数,内层循环控制每一轮比较的次数。如果相邻两个元素的顺序不正确,就交换它们的位置,直到一轮比较结束。重复进行多轮比较,直到整个数组都有序。
数据结构排序算法代码
对于数据结构的排序算法,有许多种不同的实现。以下是常见的几种排序算法的代码示例:
1. 冒泡排序(Bubble Sort):
```cpp
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// 交换元素
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
```
2. 插入排序(Insertion Sort):
```cpp
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
```
3. 选择排序(Selection Sort):
```cpp
void selectionSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// 交换元素
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
```
这些只是排序算法的简单示例,实际应用中可能需要更多的考虑和优化。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)