Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added selection sort logic in typescript #2693

Merged
merged 1 commit into from
Apr 6, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Selection_Sort/Selection_Sort.ts
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 ]