We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Day 20: Sorting
Day 20: Sorting
+ 0 comments Python:
if __name__ == '__main__': n = int(input().strip()) a = list(map(int, input().rstrip().split())) swaps = 0 for _ in range(len(a)): for i in range (len(a)-1): if a[i] > a[i+1]: a[i], a[i+1] = a[i+1], a[i] swaps += 1 print (f"Array is sorted in {str(swaps)} swaps.") print (f"First Element: {a[0]}") print (f"Last Element: {a[len(a)-1]}")
+ 0 comments Solution in Java 8
public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(bufferedReader.readLine().trim()); List<Integer> a = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(toList()); int count=0; // Write your code here for(int j=0;j<n;j++){ for(int i=0;i<n-1;i++){ if(a.get(i)>a.get(i+1)){ Collections.swap(a, i, i+1); count++; } } } System.out.println("Array is sorted in "+count+" swaps."); System.out.println("First Element: "+a.get(0)); System.out.println("Last Element: "+a.get(n-1)); bufferedReader.close(); } }
+ 0 comments int no_swap = 0 ; for(int i=0; i a.get(j)) { int temp = a.get(i); a.set(i, a.get(j)); a.set(j, temp);
no_swap++; } } if (no_swap == 0) { break; } } System.out.println("Array is sorted in "+ no_swap + " swaps."); System.out.println("First Element: " + a.get(0)); System.out.println("Last Element: " + a.get(n-1));
+ 0 comments in node.js
function main() { const n = parseInt(readLine().trim(), 10);
const a = readLine().replace(/\s+$/g, '').split(' ').map(aTemp => parseInt(aTemp, 10)); let swap = 0; for(let i = 0; i < n; i++) { for(let j = i + 1; j < n; j++) { if(a[i] > a[j]) { const temp = a[i]; a[i] = a[j]; a[j] = temp; swap++; } } } console.log("Array is sorted in " + swap + " swaps."); console.log("First Element: " + a[0]); console.log("Last Element: " + a[n - 1]);
}
+ 0 comments Java 7:
for (int i = 0; i < n; i++) { int aItem = Integer.parseInt(aTemp[i]); a.add(aItem); } int swap = 0; for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) if(a.get(i) > a.get(j)) { int temp = a.get(i); a.set(i, a.get(j)); a.set(j, temp); swap++; } } System.out.println("Array is sorted in "+swap+" swaps."); System.out.println("First Element: "+a.get(0)); System.out.println("Last Element: "+a.get(n-1));
Load more conversations
Sort 599 Discussions, By:
Please Login in order to post a comment