冒泡排序
冒泡排序是比较两个相邻元素,如果它们不符合预期的顺序就交换的一个排序过程。
冒泡排序就像水中气泡上升到水面的运动一样,数组的每个元素在每次迭代中都把当前迭中最大(或最小)的元素移动到最后,因此被称为冒泡排序。
冒泡排序的工作流程
1.第一次迭代(比较和交换)
2.后续的迭代过程
代码实现
Swift实现
import Foundation
func bubbleSort(array:inout Array<Int>) {
for i in 0 ..< array.count - 1 {
for j in 0 ..< array.count - 1 - i {
if array[j] > array[j + 1] {
array.swapAt(j, j+1)
}
}
}
}
func printBubbleSort(_ array:inout [Int]){
bubbleSort(array: &array)
print(array)
}
var arr:[Int] = [3, 2, 5, 7, 1, 5, 4, 8, 11, 0]
printBubbleSort(&arr);
Python实现
def bubbleSort(array):
for i in range(len(array)):
for j in range(0, len(array) - i - 1):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
data = [-2, 45, 0, 11, -9]
bubbleSort(data)
print('Sorted Array in Ascending Order:')
print(data)
Java的实现
import java.util.Arrays;
class Main {
static void bubbleSort(int array[]) {
int size = array.length;
for (int i = 0; i < size - 1; i++)
for (int j = 0; j < size - i - 1; j++)
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
public static void main(String args[]) {
int[] data = { -2, 45, 0, 11, -9 };
Main.bubbleSort(data);
System.out.println("Sorted Array in Ascending Order:");
System.out.println(Arrays.toString(data));
}
}
C实现
#include <stdio.h>
void bubbleSort(int array[], int size) {
for (int step = 0; step < size - 1; ++step) {
for (int i = 0; i < size - step - 1; ++i) {
if (array[i] > array[i + 1]) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int data[] = {-2, 45, 0, 11, -9};
int size = sizeof(data) / sizeof(data[0]);
bubbleSort(data, size);
printf("Sorted Array in Ascending Order:\n");
printArray(data, size);
}
C++实现
#include <iostream>
using namespace std;
void bubbleSort(int array[], int size) {
for (int step = 0; step < (size-1); ++step) {
for (int i = 0; i < size - (step-1); ++i) {
if (array[i] > array[i + 1]) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
cout << " " << array[i];
}
cout << "\n";
}
int main() {
int data[] = {-2, 45, 0, 11, -9};
int size = sizeof(data) / sizeof(data[0]);
bubbleSort(data, size);
cout << "Sorted Array in Ascending Order:\n";
printArray(data, size);
}
|