Files
c/bubblesort/main.c
T
2021-09-20 02:31:04 +05:30

58 lines
1.2 KiB
C

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int* sort(int*, int);
void swap(int*, int, int);
int DEBUG;
int main(){
char* _debug = getenv("DEBUG");
if(_debug)
DEBUG = !strcmp(_debug,"1");
//how does this even work???
int arr[] = {1,2,4,593,29,19,0};
int arr_len = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr_len);
printf("\n");
return EXIT_SUCCESS;
}
int* sort(int* arr, int length){
if(DEBUG){
printf("length of array to be sorted: %d\n", length);
printf("elements of array to be sorted: ");
for(int i=0; i<length; i++){
if(i!=0) printf(", ");
printf("%d", arr[i]);
}
}
for(int i=1; i<length; i++){
if(arr[i]>arr[i+1])
swap(arr, i, i+1);
}
if(DEBUG){
printf("=====\nelement post-sort are: ");
for(int i=0; i<length; i++){
if(i!=0) printf(", ");
printf("%d", arr[i]);
}
}
return arr;
}
void swap(int* arr, int left, int right){
if(DEBUG)
printf("\nPRESWAP\nleft is: %d; right is %d\n", arr[left],arr[right]);
int _hold = arr[left];
arr[left] = arr[right];
arr[right] = _hold;
if(DEBUG)
printf("\nPOSTSWAP\nleft is: %d; right is %d\n", arr[left],arr[right]);
}