Answers for "selection sort sorting"

C
6

selection sort

#include <bits/stdc++.h>

using namespace std; 

void selectionSort(int arr[], int n){
    int i,j,min;
    
    for(i=0;i<n-1;i++){
        min = i;
        for(j=i+1;j<n;j++){
            if(arr[j] < arr[min]){
                min = j;
            }
        }
        if(min != i){
            swap(arr[i],arr[min]);
        }
    }
}

int main()  
{  
    int arr[] = { 1,4,2,5,333,3,5,7777,4,4,3,22,1,4,3,666,4,6,8,999,4,3,5,32 };  
    int n = sizeof(arr) / sizeof(arr[0]);  

    selectionSort(arr, n);  

    for(int i = 0; i < n; i++){
        cout << arr[i] << " ";
    }

    return 0;  
}
Posted by: Guest on January-16-2021
2

selection sort

// C algorithm for SelectionSort

void selectionSort(int arr[], int n)
{
	for(int i = 0; i < n-1; i++)
	{
		int min = i;
        
		for(int j = i+1; j < n; j++)
		{
			if(arr[j] < arr[min])
            	min = j;
		}
        
		if(min != i)
		{
        	// Swap
			int temp = arr[i];
			arr[i] = arr[min];
			arr[min] = temp;
		}
	}
}
Posted by: Guest on January-05-2021
0

Selection Sort

#include<bits/stdc++.h>
using namespace std;
void print(int arr[], int n)
{
    for(int i=0;i<n;i++)
        cout<<arr[i]<<" ";
    cout<<endl;
}
void selectionSort(int arr[], int n)
{
    int i,j,min_in;
    for(i=0;i<n;i++)
    {
        min_in = i;
        for(j=i+1;j<n;j++)
            if (arr[j] < arr[min_in])
                min_in = j;
        swap(arr[i],arr[min_in]);
    }
}
int main(int argv, char* argc[])
{
    int arr[] = {5,4,10,1,6,2};
    int i,j,n,temp;
    n = sizeof(arr)/sizeof(int);
    cout<<"Unsorted Array :";
    print(arr,n);
    selectionSort(arr,n);
    cout<<"Sorted Array :";
    print(arr,n);
    return(0);
}
Posted by: Guest on January-24-2022

Code answers related to "C"

Browse Popular Code Answers by Language