Day 20 : Sorting
Solution In Java 8:
import java.io.*;import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int temp;
int n = in.nextInt();
int a[] = new int[n];
int numSwaps = 0, firstElement,lastElement;
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
numSwaps++;
}
}
if (numSwaps == 0) {
break;
}
}
System.out.println("Array is sorted in "+numSwaps+" swaps.");
System.out.println("First Element: "+a[0]);
System.out.println("Last Element: "+a[n-1]);
}
}
Solution In Python 3:
#!/bin/python3
import sys
n = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(' ')]
numSwaps = 0
for i in range(0,n):
for j in range(0,n-1):
if(a[j] > a[j+1]):
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
numSwaps = numSwaps+1
print("Array is sorted in {} swaps.".format(numSwaps))
print("First Element: {}".format(a[0]))
print("Last Element: {}".format(a[n-1]))
0 comments:
Post a Comment