improved selection sort with function style for reusability (#52)

pull/54/head
Visrut 2021-01-31 18:21:08 +05:30 committed by GitHub
parent f84976ab83
commit a6e15a9e5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 20 additions and 10 deletions

View File

@ -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]))