1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| function ArrayList(){ var arr = [] var swap = function(i,j){ var temp = arr[i] arr[i] = arr[j] arr[j] = temp } this.initial = function(array){ for(var i = 0;i < array.length;i++) arr.push(array[i]) } /*Bubble sort ascend*/ this.bubbleSort = function(){ if(arr.length < 2) return for(var i = 0;i < arr.length;i++){ for(var j = 0;j < arr.length - 1 - i;j++){ if(arr[j] > arr[j+1]) swap(j,j+1) } } } /*Select sort ascend*/ this.selectSort = function(){ if(arr.length < 2) return for(var i = 0;i < arr.length;i++){ var min = i for(var j = i;j < arr.length;j++){ if(arr[j] < arr[min]) min = j } if(arr[min] != arr[i]) swap(i,min) } } /*Insert sort ascend*/ this.insertSort = function(){ if(arr.length < 2) return for(var i = 1;i < arr.length;i++){ var k = i, temp = arr[i] while(k > 0 && temp < arr[k-1]){ arr[k] = arr[k-1] k-- } arr[k] = temp } } /*Merge sort ascend*/ var mergeSortRec = function(array){ if(array.length === 1) return array var mid = Math.floor(array.length / 2) var left = array.slice(0,mid) var right = array.slice(mid,array.length) return merge(mergeSortRec(left),mergeSortRec(right)) } var merge = function(left,right){ var array = [] var i = 0,j = 0 while(i < left.length && j < right.length){ if(left[i] < right[j]){ array.push(left[i]) i++ } else{ array.push(right[j]) j++ } } while(i < left.length){ array.push(left[i]) i++ } while(j < right.length){ array.push(right[j]) j++ } return array } this.mergeSort = function(){ if(arr.length === 1) return arr = mergeSortRec(arr) } /*Quick sort ascend*/ var quickSort = function(){ quick(arr,0,arr.length - 1) } var quickPartition = function(array,left,right){ var center = Math.floor((left + right) / 2) var l = left var r = right while(l <= r){ /*find bigger number from left of the array*/ while(array[l] < array[center]){ l++ } /*find smaller number from right of the array*/ while(array[r] > array[center]){ r-- if(l <= r){ quickSortSwap(l,r) l++ r-- } } return l } var quick = function(array,left,right){ if(array.length <= 1) return array var index = quickPartition(array,left,right) if(left < index - 1) quick(array,left,index - 1) if(right > index) quick(array,index,right) } }
|