improved selection sort with function style for reusability (#52)
parent
f84976ab83
commit
a6e15a9e5d
|
@ -1,15 +1,25 @@
|
||||||
let sort = [12,6,3,88,1,4,8]
|
function selectionSort(array) {
|
||||||
|
|
||||||
for(let i=0; i<sort.length; i++){
|
// loop through all elements except last in array
|
||||||
for(let j=0; j<sort.length; j++){
|
for(let i=0;i<array.length - 1;i++) {
|
||||||
// comparing array elements
|
let min_index = i;
|
||||||
if(sort[j]>sort[i]){
|
|
||||||
//swaping elements
|
// find minimum element index in unsorted array
|
||||||
let temp = sort[i];
|
for(let j=i+1;j<array.length;j++) {
|
||||||
sort[i]=sort[j];
|
if(array[j] < array[i]) {
|
||||||
sort[j]= temp;
|
min_index = j;
|
||||||
|
}
|
||||||
|
|
||||||
|
// swap with element at minimum index
|
||||||
|
let temp = array[min_index];
|
||||||
|
array[min_index] = array[i];
|
||||||
|
array[i] = temp;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// return sorted array
|
||||||
|
return array;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(sort)
|
// test
|
||||||
|
console.log(selectionSort([9,8,7,6,5,4,3,2,1,0]))
|
||||||
|
|
Loading…
Reference in New Issue