implements insertion sort in c and pytyhon
This commit is contained in:
parent
09e18f9ac9
commit
82d3973ade
|
@ -0,0 +1,31 @@
|
|||
#include <stdio.h>
|
||||
|
||||
void insertion_sort(int arr[], int len) {
|
||||
int temp;
|
||||
int j;
|
||||
for (int i = 1; i < len; i++) {
|
||||
temp = arr[i];
|
||||
j = i - 1;
|
||||
while (j >= 0) {
|
||||
if (temp < arr[j]) {
|
||||
arr[j + 1] = arr[j];
|
||||
}
|
||||
j--;
|
||||
}
|
||||
arr[j + 1] = temp;
|
||||
}
|
||||
}
|
||||
|
||||
void print_array(int arr[], int len) {
|
||||
printf("[ ");
|
||||
for (int i = 0; i < len; i++) {
|
||||
printf("%d ", arr[i]);
|
||||
}
|
||||
printf("]\n");
|
||||
}
|
||||
|
||||
int main() {
|
||||
int arr[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
|
||||
insertion_sort(arr, 10);
|
||||
print_array(arr, 10);
|
||||
}
|
|
@ -7,18 +7,16 @@ void swap(int *a, int *b) {
|
|||
}
|
||||
|
||||
void selection_sort(int arr[], int len) {
|
||||
int curr_low;
|
||||
int low_index = 0;
|
||||
int pass_index = 0;
|
||||
|
||||
for (int i = 0; i < len; i++) {
|
||||
low_index = i;
|
||||
for (int j = i + 1; j < len; j++) {
|
||||
if (arr[i] > arr[j]) { // if we encounter a new low
|
||||
low_index = j;
|
||||
int lo_index;
|
||||
for (int i = 0; i < len; i++) { // keep track of pass
|
||||
lo_index = i; // low index always starts as the pass iteration
|
||||
for (int j = i + 1; j < len; j++) { // keep track of array comparisons
|
||||
if (arr[j] < arr[i]) {
|
||||
lo_index = j;
|
||||
}
|
||||
}
|
||||
swap(&arr[i], &arr[low_index]);
|
||||
} // after done with this loop we swap the value at lo_index to the current pass index
|
||||
|
||||
swap(&arr[i], &arr[lo_index]);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -31,7 +29,7 @@ void print_array(int arr[], int len) {
|
|||
}
|
||||
|
||||
int main() {
|
||||
int arr[6] = {5, 3, 4, 2, 1, 7};
|
||||
selection_sort(arr, 6);
|
||||
print_array(arr, 6);
|
||||
int arr[5] = {5, 4, 3, 2, 1};
|
||||
selection_sort(arr, 5);
|
||||
print_array(arr, 5);
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
def insertion_sort(array):
|
||||
for index in range(1, len(array)):
|
||||
temp_value = array[index]
|
||||
position = index - 1
|
||||
|
||||
while position >= 0:
|
||||
if array[position] > temp_value:
|
||||
array[position + 1] = array[position]
|
||||
else:
|
||||
break
|
||||
array[position + 1] = temp_value
|
||||
|
||||
return array
|
Loading…
Reference in New Issue