implement quicksort in c again to practice and in oding to see what its like

This commit is contained in:
Emanuel Rodriguez 2023-08-17 23:20:31 -07:00
parent bd0fc7054d
commit fb08343f8c
3 changed files with 92 additions and 7 deletions

2
c/qs.c
View File

@ -38,7 +38,7 @@ void quick_sort(int arr[], int lo, int hi) {
int main() {
int array_len = 5;
int arr[5] = {5, 4, 3, 2, 1};
int arr[5] = {0, 2, 5, 1, 6};
quick_sort(arr, 0, array_len - 1);
printf("[ ");

51
c/quicksort.c Normal file
View File

@ -0,0 +1,51 @@
#include <stdio.h>
// the partition will weakly sort the array and return the index of
// the pivot
int partition(int arr[], int lo, int hi) {
int pivot_value = arr[hi];
int current_index = lo - 1;
int temp;
for (int i = lo; i < hi; i++) {
if (arr[i] <= pivot_value) {
current_index++;
temp = arr[i];
arr[i] = arr[current_index];
arr[current_index] = temp;
}
}
// once done with loop the current_index will hold
// the location where we need to place the pivot_value
current_index++;
arr[hi] = arr[current_index];
arr[current_index] = pivot_value;
return (current_index);
}
void qs(int arr[], int lo, int hi) {
if (lo < hi) {
int current_pivot = partition(arr, lo, hi);
qs(arr, lo, current_pivot - 1);
qs(arr, current_pivot + 1, hi);
}
}
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[5] = {0, 2, 5, 1, 6};
print_array(arr, 5);
qs(arr, 0, 4);
print_array(arr, 5);
return (0);
}

View File

@ -5,16 +5,50 @@ import "core:fmt"
linear_search :: proc(arr: []int, len: int, needle: int) -> bool {
for index, val in arr {
if val == needle {
return true;
return true
}
}
return false;
return false
}
partition :: proc(arr: ^[]int, lo: int, hi: int) -> int {
pivot_value := arr[hi]
current_index := lo - 1
for i := lo; i < hi; i +=1 {
if arr[i] <= pivot_value {
current_index += 1
tmp := arr[i]
arr[i] = arr[current_index]
arr[current_index] = tmp
}
}
current_index += 1
arr[hi] = arr[current_index]
arr[current_index] = pivot_value
return(current_index)
}
quick_sort :: proc(arr: ^[]int, lo: int, hi: int) {
if lo < hi {
current_pivot := partition(arr, lo, hi);
quick_sort(arr, lo, current_pivot - 1);
quick_sort(arr, current_pivot + 1, hi);
}
}
main :: proc() {
fmt.println("hello there here is a for loop");
fmt.println("hello there here is a for loop")
values: []int = {1, 2, 3, 4, 5};
res: bool = linear_search(values, 5, 2);
fmt.println(res);
values: []int = {1, 2, 3, 4, 5}
res: bool = linear_search(values, 5, 2)
fmt.println(res)
fmt.println("quicksort ----------------")
arr: []int = {0, 2, 5, 1, 6}
fmt.println(arr);
quick_sort(&arr, 0, 4);
fmt.println(arr);
}