Skip to content

Commit b62e226

Browse files
committed
selection sort
1 parent 4b0707f commit b62e226

File tree

5 files changed

+70
-0
lines changed

5 files changed

+70
-0
lines changed

2-O

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
O(n^2)
2+
O(n^2)
3+
O(n^2)

2-main.c

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include "sort.h"
4+
5+
/**
6+
* main - Entry point
7+
*
8+
* Return: Always 0
9+
*/
10+
int main(void)
11+
{
12+
int array[] = {19, 48, 99, 71, 13, 52, 96, 73, 86, 7};
13+
size_t n = sizeof(array) / sizeof(array[0]);
14+
15+
print_array(array, n);
16+
printf("\n");
17+
selection_sort(array, n);
18+
printf("\n");
19+
print_array(array, n);
20+
return (0);
21+
}

2-selection_sort.c

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include "sort.h"
2+
3+
/**
4+
* swap_ints - Swap two integers in an array.
5+
* @a: The first integer to swap.
6+
* @b: The second integer to swap.
7+
*/
8+
void swap_ints(int *a, int *b)
9+
{
10+
int tmp;
11+
12+
tmp = *a;
13+
*a = *b;
14+
*b = tmp;
15+
}
16+
17+
/**
18+
* selection_sort - Sort an array of integers in ascending order
19+
* using the selection sort algorithm.
20+
* @array: An array of integers.
21+
* @size: The size of the array.
22+
*
23+
* Description: Prints the array after each swap.
24+
*/
25+
void selection_sort(int *array, size_t size)
26+
{
27+
int *min;
28+
size_t i, j;
29+
30+
if (array == NULL || size < 2)
31+
return;
32+
33+
for (i = 0; i < size - 1; i++)
34+
{
35+
min = array + i;
36+
for (j = i + 1; j < size; j++)
37+
min = (array[j] < *min) ? (array + j) : min;
38+
39+
if ((array + i) != min)
40+
{
41+
swap_ints(array + i, min);
42+
print_array(array, size);
43+
}
44+
}
45+
}

select

16.6 KB
Binary file not shown.

sort.h

+1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ void print_list(const listint_t *list);
3636
/*sorting algorithms */
3737
void bubble_sort(int *array, size_t size);
3838
void insertion_sort_list(listint_t **list);
39+
void selection_sort(int *array, size_t size);
3940
void merge_sort(int *array, size_t size);
4041
void heap_sort(int *array, size_t size);
4142
void radix_sort(int *array, size_t size);

0 commit comments

Comments
 (0)