HR30 Day 20: Sorting

1 개요[ | ]

HR30 Day 20: Sorting

해커랭크 30 Days of Code
문제 풀이
20-29 Day e
HR30 Day 20: Sorting

HR30 Day 21: Generics

HR30 Day 22: Binary Search Trees

HR30 Day 23: BST Level-Order Traversal

HR30 Day 24: More Linked Lists

HR30 Day 25: Running Time and Complexity

HR30 Day 26: Nested Logic

HR30 Day 27: Testing

HR30 Day 28: RegEx, Patterns, and Intro to Databases

HR30 Day 29: Bitwise AND

2 Java[ | ]

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 n = in.nextInt();
        int[] a = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
        // Write Your Code Here
        int numberOfSwaps = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n - 1; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                    numberOfSwaps++;
                }
            }
            if (numberOfSwaps == 0) break;
        }
        System.out.printf( "Array is sorted in %d swaps.\n", numberOfSwaps );
        System.out.printf( "First Element: %d\n", a[0] );
        System.out.printf( "Last Element: %d\n", a[n-1] );
    }
}

3 PHP[ | ]

<?php
$handle = fopen ("php://stdin", "r");
fscanf($handle, "%d",$n);
$a_temp = fgets($handle);
$a = explode(" ",$a_temp);
$a = array_map('intval', $a);
// Write Your Code Here
$numberOfSwaps = 0;
for($i=0; $i<$n; $i++) {
    for($j=0; $j<$n-1; $j++) {
        if ($a[$j] > $a[$j+1]) {
            $temp = $a[$j];
            $a[$j] = $a[$j+1];
            $a[$j+1] = $temp;
            $numberOfSwaps++;
        }
    }
    if ($numberOfSwaps == 0) break;
}
echo "Array is sorted in ".$numberOfSwaps." swaps.\n";
echo "First Element: ".$a[0]."\n";
echo "Last Element: ".$a[$n-1]."\n";
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}