File tree Expand file tree Collapse file tree 2 files changed +15
-0
lines changed Expand file tree Collapse file tree 2 files changed +15
-0
lines changed Original file line number Diff line number Diff line change
1
+ // It sorts the array by repeatedly comparing the adjacent elements and swapping them if they are in the wrong order
2
+ // Time complexity is O(N^2)
3
+ // Auxiliary space is O(1)
4
+
1
5
pub fn bubble_sort < T : Ord > ( array : & mut [ T ] ) {
2
6
for i in 0 ..array. len ( ) {
7
+ // Last i elements are already in place
3
8
for j in 0 ..array. len ( ) - 1 - i {
4
9
if array[ j] > array[ j + 1 ] {
5
10
array. swap ( j, j + 1 ) ;
Original file line number Diff line number Diff line change
1
+ // Insertion sort divides the array into sorted and unsorted parts.
2
+ // Values from the unsorted parts are placed in the correct position in the sorted part
3
+ // time complexity is O(N^2)
4
+ // Auxiliary space is O(1)
5
+
1
6
pub fn insertion_sort < T : Ord > ( array : & mut [ T ] ) {
7
+ // initialise the array
2
8
for i in 0 ..array. len ( ) {
3
9
let mut j = i;
10
+ // Move elements of arr[0..i-1],
11
+ // that are greater than key, to one
12
+ // position ahead of their
13
+ // current position
4
14
while j > 0 && array[ j] < array[ j - 1 ] {
5
15
array. swap ( j, j - 1 ) ;
6
16
j -= 1 ;
You can’t perform that action at this time.
0 commit comments