|
| 1 | +//Simple Bubble Sort implementation |
| 2 | +function bubbleSort(arr){ |
| 3 | + var len = arr.length; |
| 4 | + |
| 5 | + for(var i=0; i<len-1; i++){ |
| 6 | + // Last i elements are already in place, so the inner loops will run until it reaches the last i elements |
| 7 | + for(var j=0; j<len-i-1;j++){ |
| 8 | + //To Sort in decreasing order, change the comparison operator to '<' |
| 9 | + if(arr[j] > arr[j+1]){ |
| 10 | + var tmp = arr[j]; |
| 11 | + arr[j] = arr[j+1]; |
| 12 | + arr[j+1] = tmp; |
| 13 | + } |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + return arr; |
| 18 | +} |
| 19 | + |
| 20 | +//Following is a slightly modified bubble sort implementation, which tracks the list with a flag to check if it is already sorted |
| 21 | +function modifiedBubbleSort(arr){ |
| 22 | + var len = arr.length; |
| 23 | + |
| 24 | + for(var i=0; i<len-1; i++){ |
| 25 | + var flag = false; //Taking a flag variable |
| 26 | + |
| 27 | + // Last i elements are already in place, so the inner loops will run until it reaches the last i elements |
| 28 | + for(var j=0; j<len-i-1;j++){ |
| 29 | + //To Sort in decreasing order, change the comparison operator to '<' |
| 30 | + if(arr[j] > arr[j+1]){ |
| 31 | + var tmp = arr[j]; |
| 32 | + arr[j] = arr[j+1]; |
| 33 | + arr[j+1] = tmp; |
| 34 | + |
| 35 | + flag = true; //Setting the flag, if swapping occurs |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + //If not swapped, that means the list has already sorted |
| 40 | + if(!flag) break; |
| 41 | + } |
| 42 | + |
| 43 | + return arr; |
| 44 | +} |
| 45 | + |
| 46 | + |
| 47 | +/** Testing Bubble sort algorithm **/ |
| 48 | +/** |
| 49 | + * Returns a random integer between min (inclusive) and max (inclusive) |
| 50 | + * Using Math.round() will give you a non-uniform distribution! |
| 51 | + */ |
| 52 | +function getRandomInt(min, max) { |
| 53 | + return Math.floor(Math.random() * (max - min + 1)) + min; |
| 54 | +} |
| 55 | + |
| 56 | +var arr = []; |
| 57 | + |
| 58 | +for(var i=0;i<10;i++){ |
| 59 | + arr.push(getRandomInt(1, 100)); |
| 60 | +} |
| 61 | +console.log("Unsorted array: "); |
| 62 | +console.log(arr); //printing unsorted array |
| 63 | + |
| 64 | +arr = bubbleSort(arr); |
| 65 | +// arr = modifiedBubbleSort(arr); |
| 66 | +console.log("Sorted array: "); |
| 67 | +console.log(arr); //printing sorted array |
0 commit comments