Skip to content

Commit

Permalink
Update selectionsort.c
Browse files Browse the repository at this point in the history
  • Loading branch information
ajayram515 authored Oct 12, 2017
1 parent 4f833d6 commit 4ab6324
Showing 1 changed file with 45 additions and 24 deletions.
69 changes: 45 additions & 24 deletions Sorting Algorithms/C:C++/selectionsort.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,50 @@ Write a function that selection sorts the array. Print the elements of sorted ar
2.Take Another N numbers as input and store them in an Array.
3.Sort the array using Selection Sort and print that Array. */

#include<iostream>

using namespace std;

int main(){
int n,i,j;
cin>>n;
int a[10];
for(i=0;i<n;i++){
cin>>a[i];
}
for(i=0;i<n-1;i++){
int min=i;
for(j=i;j<n;j++){
if(a[j]<a[min]){
min=j;
}
}
swap(a[i],a[min]);

}
for(i=0;i<n;i++){
cout<<a[i]<<endl;
// C program for implementation of selection sort
#include <stdio.h>

void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)
{
int i, j, min_idx;

// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
return 0;
}

/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

0 comments on commit 4ab6324

Please sign in to comment.