Write a program to sort an array. Use of selection sort.
Example 1:
Input: arr[]= {3,2,5,4,1}
Output: 1 2 3 4 5
Approach:
Java
import java.util.Arrays;public class SelectionSorting {public static void main(String args[]) throws Exception {int arr[] = { 3, 2, 5, 4, 1 };selectionSorting(arr, arr.length);}static void selectionSorting(int[] arr, int N) {for (int i = 0; i < N; i++) {int min = i;for (int j = i + 1; j < N; j++) {if (arr[min] > arr[j]) {min = j;}}// Swapping elementint tmp = arr[min];arr[min] = arr[i];arr[i] = tmp;}// Sorted array printingArrays.stream(arr).forEach(e -> System.out.print(e + " "));}}//Time Complexity: O(n^2)//Space Complexity: O(1)
C++
#include <bits/stdc++.h>using namespace std;//Function to sort the given//arrayvoid selectionSort(int arr[],int n){int minIndex;for(int i=0;i<n-1;i++){minIndex=i;for(int j=i+1;j<n;j++){if(arr[j]<arr[minIndex]){minIndex=j;}}int temp=arr[minIndex];arr[minIndex]=arr[i];arr[i]=temp;}}int main(){int arr[]={3,2,5,4,1};int n=sizeof(arr)/sizeof(arr[0]);selectionSort(arr,n);cout<<"Sorted Array is ";for(int i=0;i<n;i++)cout<<arr[i]<<" ";return 0;}//Time Complexity: O(n^2)//Space Complexity:O(1)
No comments:
Post a Comment