动图展示
算法时间复杂度:o(n*n)
C++
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include<iostream>
#define ArrayLen 10
using namespace std;
void swap(int* array, char i, char j);
void BubbleSort(int* array);
void main()
{
int array[ArrayLen] = { 2, 3, 6, 5, 4, 1, 7, 8, 9, 0 };
for (int i = 0; i < ArrayLen; i++)
{
cout << array[i] << endl;
}
BubbleSort(array);
for (int i = 0; i < ArrayLen; i++)
{
cout << array[i] << endl;
}
}
void BubbleSort(int* array)
{
int * local_array = array;
for (int i = 0; i < ArrayLen; i++)
{
for (int j = 0; j < ArrayLen - i - 1; j++)
{
if (local_array[j] < local_array[j+1])
{
swap(local_array,j,j+1);
}
}
}
}
void swap(int* array, char i , char j)
{
int * local_array = array;
char temp;
temp = local_array[i];
local_array[i] = local_array[j];
local_array[j] = temp;
}
Python