forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added selection sort logic in typescript (jainaman224#2693)
- Loading branch information
1 parent
74b9f28
commit 0e2fd5e
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
// function for selection sort logic | ||
function Selection_Sort(numbers: number[]) : number[]{ | ||
|
||
let i: number; | ||
let j: number; | ||
let min: number; | ||
let temp: number; | ||
|
||
// outer loop to traverse through each element | ||
for(i = 0; i < numbers.length - 1; i++){ | ||
min = i; | ||
|
||
// inner loop finds the minimum element and puts it in the beginning. | ||
for(j = i + 1; j < numbers.length; j++){ | ||
if(numbers[j] < numbers[min]){ | ||
min = j; | ||
} | ||
} // inner loop ends | ||
|
||
if(i !== min){ | ||
temp = numbers[i]; | ||
numbers[i] = numbers[min]; | ||
numbers[min] = temp; | ||
} | ||
} // outer loop ends | ||
|
||
return numbers; | ||
} | ||
|
||
const numbers: number[] = [10, 9, 8, 1, 5, 2, 4, 7, 3]; | ||
|
||
console.log(Selection_Sort(numbers)); | ||
|
||
// INPUT [10, 9, 8, 1, 5, 2, 4, 7, 3] | ||
// OUTPUT [ 1, 2, 3, 4, 5, 7, 8, 9, 10 ] |