写出用直接插入排序将关键字序列{54,23, 89,48,64,50, 25,90,34}排序过程的每-趟结果,并编码实现直接插入排序算法。
时间: 2024-03-06 17:49:01 浏览: 19
好的,以下是直接插入排序的过程:
第1趟:23 54 89 48 64 50 25 90 34
第2趟:23 54 89 48 64 50 25 90 34
第3趟:23 48 54 89 64 50 25 90 34
第4趟:23 48 54 64 89 50 25 90 34
第5趟:23 48 50 54 64 89 25 90 34
第6趟:23 25 48 50 54 64 89 90 34
第7趟:23 25 34 48 50 54 64 89 90
以下是直接插入排序的Python实现:
```python
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
arr = [54, 23, 89, 48, 64, 50, 25, 90, 34]
sorted_arr = insertion_sort(arr)
print(sorted_arr)
```
输出结果为:[23, 25, 34, 48, 50, 54, 64, 89, 90]
相关问题
用java写出用直接插入排序将关键字序列{54,23, 89,48,64,50, 25,90,34}排序过程的每-趟结果,并编码实现直接插入排序算法。
好的,以下是直接插入排序的过程:
第1趟:23 54 89 48 64 50 25 90 34
第2趟:23 54 89 48 64 50 25 90 34
第3趟:23 48 54 89 64 50 25 90 34
第4趟:23 48 54 64 89 50 25 90 34
第5趟:23 48 50 54 64 89 25 90 34
第6趟:23 25 48 50 54 64 89 90 34
第7趟:23 25 34 48 50 54 64 89 90
以下是直接插入排序的Java实现:
```java
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {54, 23, 89, 48, 64, 50, 25, 90, 34};
insertionSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; 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;
}
}
}
```
输出结果为:23 25 34 48 50 54 64 89 90
输入一组关键字序列实现下列排序:实现简单选择排序、直接插入排序和冒泡排序。 用C++写出编码
好的,下面是代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 简单选择排序
void selectSort(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[minIndex]) {
minIndex = j;
}
}
swap(nums[i], nums[minIndex]);
}
}
// 直接插入排序
void insertSort(vector<int>& nums) {
int n = nums.size();
for (int i = 1; i < n; i++) {
int j = i - 1;
int temp = nums[i];
while (j >= 0 && nums[j] > temp) {
nums[j + 1] = nums[j];
j--;
}
nums[j + 1] = temp;
}
}
// 冒泡排序
void bubbleSort(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n - 1; i++) {
bool flag = false;
for (int j = 0; j < n - i - 1; j++) {
if (nums[j] > nums[j + 1]) {
swap(nums[j], nums[j + 1]);
flag = true;
}
}
if (!flag) {
break;
}
}
}
int main() {
vector<int> nums = {5, 3, 8, 6, 4};
cout << "Original nums: ";
for (auto num : nums) {
cout << num << " ";
}
cout << endl;
selectSort(nums);
cout << "After select sort: ";
for (auto num : nums) {
cout << num << " ";
}
cout << endl;
nums = {5, 3, 8, 6, 4};
insertSort(nums);
cout << "After insert sort: ";
for (auto num : nums) {
cout << num << " ";
}
cout << endl;
nums = {5, 3, 8, 6, 4};
bubbleSort(nums);
cout << "After bubble sort: ";
for (auto num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
```
这里我们定义了三个排序函数,分别为简单选择排序、直接插入排序和冒泡排序。在 `main()` 函数中,我们首先定义了一个初始的整数数组 `nums`,然后分别对其进行了三种排序,最后输出排序后的结果。