0% found this document useful (0 votes)
2 views

Selection sort

The document contains C code implementations for two sorting algorithms: selection sort and bubble sort. It includes functions to sort an array and print its elements, with examples of how to take user input for the array size and elements. Both sorting methods demonstrate how to sort an array and display the results before and after sorting.

Uploaded by

suzana9225
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Selection sort

The document contains C code implementations for two sorting algorithms: selection sort and bubble sort. It includes functions to sort an array and print its elements, with examples of how to take user input for the array size and elements. Both sorting methods demonstrate how to sort an array and display the results before and after sorting.

Uploaded by

suzana9225
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Selection sort:

#include<stdio.h>
void selectionsort(int arr[], int n){
int i, j, index, temp;
for(i = 0; i < n -1; i++){
index = i;
for(j = i + 1; j < n; j++){
if(arr[j] < arr[index]){
index = j;
}
}
if(index != i){
temp = arr[index];
arr[index] = arr[i];
arr[i] = temp;
}
}
}
void printArray(int arr[], int n){
for(int i = 0; i < n; i ++){
printf("%d\t", arr[i]);
}
printf("\n");
}
int main()
{
int a[]= {64, 25, 12, 22, 11};
int n = sizeof(a) / sizeof(a[0]);
printf("Array before sorting:\n");
printArray(a, n);
selectionsort(a, n);
printf("Array after sorting:\n");
printArray(a, n);
}

Taking input from the user:


int main()
{
//taking input from user
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
printf("Enter the elements:\n");
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
printf("Array before sorting:\n");
printArray(a, n);
selectionsort(a, n);
printf("Array after sorting:\n");
printArray(a, n);
}

Bubble sort:
#include<stdio.h>
void bubbleSort(int arr[], int n){
for(int i = 0; i < n; i++){
for(int j = 0; j< n-1-i; j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void printArray(int arr[], int n){
for(int i = 0; i < n; i++){
printf("%d\t", arr[i]);
}
printf("\n");
}
int main()
{
int a[] ={10,9,1,2,3,8,6,7,4,5};
int n = sizeof(a)/ sizeof(a[0]);
printf("Array before sorting:\n");
printArray(a,n);
printf("Array after sorting:\n");
bubbleSort(a, n);
printArray(a, n);
}

You might also like