write a sorting code in c++
时间: 2023-02-24 15:50:17 浏览: 81
以下是一个在 C 语言中实现排序的代码:
```
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
for (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;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
```
这是一个冒泡排序代码,它是通过比较相邻元素的大小,交换它们的位置,使最大元素逐渐“浮”到数组的末尾,从而实现排序的目的。
相关问题
Write fast sorting in C++
快速排序是一种常用的排序算法,它通过分治法对数据进行排序。它选择一个基准数,并将数组中小于基准数的元素放在它的左边,大于基准数的元素放在它的右边,然后递归地对左右两个子数组进行排序。
C语言中的快速排序代码如下:
```
void quickSort(int arr[], int left, int right)
{
int i, j, pivot, temp;
if (left < right)
{
pivot = left;
i = left;
j = right;
while (i < j)
{
while (arr[i] <= arr[pivot] && i < right)
{
i++;
}
while (arr[j] > arr[pivot])
{
j--;
}
if (i < j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
temp = arr[pivot];
arr[pivot] = arr[j];
arr[j] = temp;
quickSort(arr, left, j - 1);
quickSort(arr, j + 1, right);
}
}
```
bubble sorting code
Here is an example of bubble sort code in Python:
```
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
```
This code defines a function `bubble_sort` that takes an array `arr` as input and returns the sorted array using the bubble sort algorithm. The function first determines the length of the array `n`. It then iterates over the array `n` times using a nested loop, comparing adjacent elements and swapping them if they are in the wrong order. The largest element "bubbles up" to the end of the array on each iteration, so the inner loop only needs to go up to `n-i-1` on the `i`th iteration. After all iterations, the sorted array is returned.