function bubble_sort (array, length) { var i, j; for(i from 0 to length-1){ for(j from 0 to length-1-i){ if (array[j] > array[j+1]) swap(array[j], array[j+1]) } } }
#include<stdio.h> voidbubble_sort(int arr[], int len){ int i, j, temp; for (i = 0; i < len - 1; i++) for (j = 0; j < len - 1 - i; j++) if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } intmain(){ int arr[] = { 22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70 }; int len = (int) sizeof(arr) / sizeof(*arr); bubble_sort(arr, len); int i; for (i = 0; i < len; i++) printf("%d ", arr[i]); return0; }
Python
defbubble(List): for j in range(len(List) - 1, 0, -1): for i in range(0, j): if List[i] > List[i+1]: List[i], List[i+1] = List[i+1], List[i] return List
Java
publicstaticvoidselection_sort(int[] arr){ int temp = 0; int size = numbers.length; for(int i = 0 ; i < size-1; i ++) { for(int j = 0 ;j < size-1-i ; j++) { if(numbers[j] > numbers[j+1]) { temp = numbers[j]; numbers[j] = numbers[j+1]; numbers[j+1] = temp; } } } }
JavaScript
Array.prototype.bubble_sort = function() { var i, j, temp; for (i = 0; i < this.length - 1; i++) for (j = 0; j < this.length - 1 - i; j++) if (this[j] > this[j + 1]) { temp = this[j]; this[j] = this[j + 1]; this[j + 1] = temp; } returnthis; }; var num = [22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70]; num.bubble_sort(); for (var i = 0; i < num.length; i++) document.body.innerHTML += num[i] + " ";