现有数组a[8]={1,3,8,9,6,2,4,7},请使用编写冒泡排序算法实现从小到大排序。
时间: 2024-04-07 18:24:46 浏览: 47
以下是使用冒泡排序算法实现从小到大排序的代码:
```python
a = [1, 3, 8, 9, 6, 2, 4, 7]
for i in range(len(a)-1):
for j in range(len(a)-1-i):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
print("排序后的数组:", a)
```
输出结果为:[1, 2, 3, 4, 6, 7, 8, 9]
相关问题
现有数组a[8]={1,3,8,9,6,2,4,7},请使用编写折半算法查找6的位置。
以下是使用折半算法查找数组中元素位置的示例代码:
```c
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 3, 8, 9, 6, 2, 4, 7};
int target = 6;
int size = sizeof(arr) / sizeof(arr[0]);
int position = binarySearch(arr, 0, size - 1, target);
if (position != -1) {
printf("The position of %d is %d\n", target, position);
} else {
printf("%d is not found in the array\n", target);
}
return 0;
}
```
现有数组a[8]={1,3,8,9,6,2,4,7},请使用编写直接插入排序算法实现从小到大排序。
以下是使用直接插入排序算法对数组a进行从小到大排序的示例代码:
```c
#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int a[8] = {1, 3, 8, 9, 6, 2, 4, 7};
int n = sizeof(a) sizeof(a[0]);
insertionSort(a, n);
printf("排序后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
return 0;
}
```
运行结果:
排序后的数组:1 2 3 4 6 7 8 9