# 算法学习笔记（python&amp;c++实现）--冒泡排序&amp;选择排序

xiaoxiao2021-03-01  12

# 算法学习笔记–冒泡排序&选择排序

### 冒泡排序

python版本：

import numpy as np def bubbleSort(arr): for i in range(len(arr)): for j in range(len(arr)-i-1): if arr[j+1] < arr[j]: tmp = arr[j] arr[j] = arr[j+1] arr[j+1] = tmp return arr if __name__ == "__main__": arr1 = np.array([5,4,3,2,1]) print bubbleSort(arr1)

c++版本：

#include<iostream> void bubbleSort(int *arr,int length){ for (int i = 0; i < length; i++){ for (int j = 0; j < length-i-1; j++){ if (arr[j+1]<arr[j]){ int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } } int main(){ int array[] = {6,5,4,3,2,1}; int length = sizeof(array)/sizeof(array[0]); bubbleSort(array, length); for (int i=0; i < sizeof(array)/sizeof(array[0]); i++){ std::cout<<array[i]<<std::endl; } return 0; }

### 选择排序

import numpy as np def selectiveSort(arr): for i in range(len(arr)): minIndex = i for j in range(i+1,len(arr)): if arr[j]<arr[minIndex]: tmp = arr[j] arr[j] = arr[minIndex] arr[minIndex] = tmp return arr if __name__ == "__main__": arr = np.array([5,4,3,2,1]) print selectiveSort(arr)

c++版本：

#include <iostream> void selectiveSort(int *arr,int length){ for (int i=0; i<length; i++){ int minIndex = i; for (int j=i+1; j<length; j++){ if(arr[j]<arr[minIndex]){ int tmp = arr[j]; arr[j] = arr[minIndex]; arr[minIndex] = tmp; } } } } int main() { int arr[] = {5,4,3,2,1}; int length = sizeof(arr)/sizeof(arr[0]); selectiveSort(arr,length); for (int i=0; i<length; i++){ std::cout<<arr[i]<<std::endl; } return 0; }