I've written this sorting algorithm in C. It looks for the element with the max value every iteration and adds it to the end of the array, swapping it with other smaller elements. This way, by almost n
swaps, an n
element array can be sorted.
#include <stdio.h>
int max(int arr1[],int l){
int max = 0;
for(int i = 0; i <= l;i++)
max = (arr1[i] > arr1[max]) ? (i) : (max);
return max;
}
void swap(int arr[], int a,int b){
if(arr[a] != arr[b]){
arr[a] += arr[b];
arr[b] = arr[a] - arr[b];
arr[a] -= arr[b];
}
}
int main(){
int arr[] = {1,5,7,2,8,9,10,32,4};
int len = sizeof(arr) / sizeof(arr[0]);
for(int i = 0; i < len; i++)
swap(arr,(len - i - 1),max(arr,(len - i -1)));
printf("\nSorted Array:\n");
for(int i = 0; i < len;i++)
printf("%d ",arr[i]);
}
Any suggestions/constructive criticism are very welcome. I'm a beginner, please point out any mistakes I made.