Last active
August 29, 2015 14:15
-
-
Save ababup1192/6e596745904074dfbba8 to your computer and use it in GitHub Desktop.
Sort I - Selection Sort http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_2_B
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; | |
int minj; | |
int i, j; | |
for(i=0;i<n-1;i++){ | |
minj = i; | |
for(j=i;j<n;j++){ | |
if(A[minj] > A[j]){ | |
minj = j; | |
} | |
} | |
if(i != minj){ | |
int tmp; | |
tmp = A[i]; | |
A[i] = A[minj]; | |
A[minj] = tmp; | |
count++; | |
} | |
} | |
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 = ssort(list) | |
println(sortedList.mkString(" ")) | |
def foward(list: List[Int]): List[Int] = { | |
if(list == Nil){ | |
Nil | |
}else{ | |
// もちろん list.min というListの最小値を求める関数もアリ | |
val minValue = list.foldLeft(Int.MaxValue){(preMin, n) => Math.min(preMin, n)} | |
if(list.head != minValue){ | |
// 最小値を先頭にし、残りの要素は元のリストから最小値のdiff(集合の差)を取ったリスト。 | |
minValue :: (list diff List(minValue)) | |
}else{ | |
list | |
} | |
} | |
} | |
def ssort(list: List[Int]): List[Int] = { | |
list match{ | |
case Nil => Nil | |
case List(x) => List(x) | |
case xs => | |
foward(xs) match{ | |
case Nil => Nil | |
case y :: ys => | |
y :: ssort(ys) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment