Last active
April 28, 2016 15:28
-
-
Save ababup1192/5af9bcf81ddf338202d4 to your computer and use it in GitHub Desktop.
Sort I - Bubble Sort http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_2_A
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Main{ | |
public static void main(String[] args){ | |
Scanner scan = new Scanner(System.in); | |
int n = scan.nextInt(); | |
int A[] = new int[100]; | |
for(int i=0;i<n;i++){ | |
A[i] = scan.nextInt(); | |
} | |
int count = 0; | |
boolean flag = true; | |
while(flag){ | |
flag = false; | |
for(int i=n-1;i>=1;i--){ | |
if(A[i] < A[i-1]){ | |
count++; | |
// 要素の交換 | |
int tmp = A[i]; | |
A[i] = A[i-1]; | |
A[i-1] = tmp; | |
flag = true; | |
} | |
} | |
} | |
printArray(A, n); | |
System.out.println(count); | |
} | |
// スペース区切りで表示 | |
public static void printArray(int A[], int n){ | |
int i; | |
for(i=0;i<n-1;i++){ | |
System.out.print(A[i] + " "); | |
} | |
System.out.println(A[i]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.io._ | |
object Main extends App { | |
val n = StdIn.readInt | |
val list = readLine.split(" ").map(_.toInt).toList | |
val sortedList = bsort(list) | |
println(sortedList.mkString(" ")) | |
// 関数リテラルにして、matchを省略 | |
// http://www.ne.jp/asahi/hishidama/home/tech/scala/match.html#h_omit | |
def bswap: (List[Int]) => List[Int] = { | |
case Nil => Nil | |
case List(x) => List(x) | |
case x :: xs => | |
// バインド時パターンマッチ(なんて言うんだろ?) | |
val y :: ys = bswap(xs) | |
// swap | |
if(x>y){ | |
y :: x :: ys | |
} | |
else{ | |
x :: y :: ys | |
} | |
} | |
def bsort: (List[Int]) => List[Int] = { | |
case Nil => Nil | |
case List(x) => List(x) | |
case xs => | |
val y :: ys = bswap(xs) | |
y :: bsort(ys) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment