Created
January 15, 2023 15:37
-
-
Save outlinepix/71473f56e2a566b61a87bdca61879855 to your computer and use it in GitHub Desktop.
Selection sort implementation in c language (Snobbish)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <assert.h> | |
/* uncomment line below if need to see debug info */ | |
/* #define DEBUG */ | |
void selectionSort(int numbers[], int length); | |
int main(int argc, char *argv[]) | |
{ | |
int numbers[] = {2, 100, 25, 15, 10, 5, 18, 88}; | |
size_t length = sizeof(numbers) / sizeof(int); | |
printf("Before selection sort\n"); | |
for (size_t i = 0; i < length; i++) | |
{ | |
printf("[%d] ", numbers[i]); | |
} | |
selectionSort(numbers, length); | |
printf("\nAfter selection sort\n"); | |
for (size_t i = 0; i < length; i++) | |
{ | |
printf("[%d] ", numbers[i]); | |
} | |
printf("\n"); | |
return 0; | |
} | |
void selectionSort(int *numbers, int length) | |
{ | |
for (size_t i = 0; i < length; i++) | |
{ | |
int min = numbers[i]; | |
int index = 0; | |
for (size_t j = i; j < length; j++) | |
{ | |
#ifdef DEBUG | |
printf("[%d] ", numbers[j]); | |
#endif | |
if (min >= numbers[j]) | |
{ | |
min = numbers[j]; | |
index = j; | |
} | |
} | |
int temp = numbers[i]; | |
numbers[i] = numbers[index]; | |
numbers[index] = temp; | |
#ifdef DEBUG | |
printf("%d \n", min); | |
printf("\n"); | |
#endif | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment