Write a program to sort the array in ascending order.
Example 1:
Input :arr[]={3,1,4,12,6,9,2}
Output: 1 2 3 4 6 9 12
Approach:
Java
import java.util.Arrays;public class SortArrayInAsc {public static void main(String[] args) {int arr[] = { 3, 1, 4, 12, 6, 9,2 };sortingAsc(arr, arr.length);Arrays.stream(arr).forEach(e -> System.out.print(e + " "));}static void sortingAsc(int[] arr, int N) {for (int i = 0; i < N; i++) {int min = i;for (int j = i + 1; j < N; j++) {// assending orderif (arr[min] > arr[j]) {min = j;}}// Swapping elementint tmp = arr[min];arr[min] = arr[i];arr[i] = tmp;}}}//Time Complexity: O(n^2)//Space Complexity: O(1)
C++
#include <bits/stdc++.h>using namespace std;//function to sort the array//in ascending ordervoid sortingAsc(int arr[], int N){for (int i = 0; i < N; i++){int min = i;for (int j = i + 1; j < N; j++) {// ascending orderif (arr[min] >arr[j]) {min = j;}}// Swapping elementint tmp = arr[min];arr[min] = arr[i];arr[i] = tmp;}}int main(){int arr[] = { 3, 1, 4, 12, 6, 9,2 };int n=sizeof(arr)/sizeof(arr[0]);sortingAsc(arr, n);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