BOJ 2750 수 정렬하기

1 개요[ | ]

BOJ 2750 수 정렬하기
  • 삽입 정렬, 거품 정렬 등의 간단한 정렬 알고리즘을 구현해 봅니다
  • 알고리즘 분류: 정렬

2 C++[ | ]

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int arr[1000];
    int N;
    cin >> N;
    for(int i=0; i<N; i++) {
        cin >> arr[i];
    }
    sort(arr, arr+N);
    for(int i=0; i<N; i++) {
        cout << arr[i] << '\n';
    }
}
#include <iostream>
using namespace std;

int main() {
    int arr[1000];
    int N, i, j, temp;
    cin >> N;
    for(i=0; i<N; i++) {
        cin >> arr[i];
    }
    for(i=0; i<N; i++) {
        for(j=i+1; j<N; j++) {
            if( arr[i] > arr[j] ) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    for(i=0; i<N; i++) {
        cout << arr[i] << '\n';
    }
}

3 Java[ | ]

거품정렬
import java.util.Scanner;
public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int i, j, temp, n = sc.nextInt();
        int[] arr = new int[n];
        for(i=0; i<n; i++) arr[i] = sc.nextInt();

        for(i=0; i<n; i++) {
            for(j=i+1; j<n; j++) {
                if( arr[i] > arr[j] ) {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        for(i=0; i<n; i++) System.out.println( arr[i] );
    }
}

4 PHP[ | ]

거품정렬
<?php
$n = intval(fgets(STDIN));
$arr = [];
for($i=0; $i<$n; $i++) $arr[$i] = intval(fgets(STDIN));
for($i=0; $i<$n; $i++) {
    for($j=$i+1; $j<$n; $j++) {
        if( $arr[$i] > $arr[$j] ) {
            $temp = $arr[$i];
            $arr[$i] = $arr[$j];
            $arr[$j] = $temp;
        }
    }
}
for($i=0; $i<$n; $i++) echo $arr[$i] . "\n";
<?php
function bubble_sort(&$arr) {
	$size = count($arr);
	for($i=0; $i<$size-1; $i++) {
		for($j=1; $j<$size-$i; $j++) {
			if($arr[$j-1] > $arr[$j]) {
				$temp = $arr[$j-1];
				$arr[$j-1] = $arr[$j];
				$arr[$j] = $temp;
			}
		}
	}
}
$n = intval(fgets(STDIN));
$arr = [];
for($i=0; $i<$n; $i++) $arr[] = intval(fgets(STDIN));
bubble_sort($arr);
for($i=0; $i<$n; $i++) echo $arr[$i] . "\n";

5 Python[ | ]

삽입정렬
def insertion_sort(arr):
	for i in range(1, len(arr)):
		j = i-1
		key = arr[i]
		while arr[j]>key and j>=0:
			arr[j+1] = arr[j]
			j -= 1
		arr[j+1] = key
n = int(input())
a = [int(input()) for i in range(n)]
insertion_sort( a )
[print( ele ) for ele in a]
거품정렬
def bubble_sort(arr):
	length = len(arr)-1
	for i in range(length):
		for j in range(length-i):
			if arr[j] > arr[j+1]:
				arr[j], arr[j+1] = arr[j+1], arr[j]
n = int(input())
a = [int(input()) for i in range(n)]
bubble_sort( a )
[print( ele ) for ele in a]
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}