K smallest Number
Selection Sort
public class KSmallesFinder {
public static void main(String[] args) {
int ns[] = {49, 38, 65, 97, 76, 13, 27, 49, 55, 04};
//}
for(int k : findKthSelection(ns, 10)) {
System.out.println(k);
}
}
private static int[] findKthSelection(int[] ns, int k){
int[] ks = new int[k];
// selection1(ns);
// selection2(ns, k);
int ns1[] = new int[ns.length + 1];
for(int i = 0 ; i < ns.length; i++){
ns1[i + 1] = ns[i];
}
//insertSort1(ns1);
//insertSort2(ns);
//bubble(ns);
shellSor(ns);
for(int i = 0 ; i < k; i++){
ks[i] = ns[i];
}
return ks;
}
private static void selection1(int[] ns){
for(int i = 0; i < ns.length; i++){
int min = ns[i];
int minpos = i;
for(int j = i + 1; j < ns.length; j++){
if(min > ns[j]){
min = ns[j];
minpos = j;
}
}
if(i != minpos){
swap(ns, i, minpos);
}
}
}
private static void swap(int[] ns, int i, int j){
int tmp = ns[j];
ns[j] = ns[i];
ns[i] = tmp;
}
private static void selection2(int[] ns, int k){
int count = 0;
for(int i = 0; i < ns.length; i++ ){
int min = ns[i];
int minpos = i;
for(int j = i + 1; j < ns.length; j++){
if(min > ns[j]){
min = ns[j];
minpos = j;
}
}
if(i != minpos){
swap(ns, i, minpos);
}
if(++count>k){
break;
}
}
}
//ns[0] is standee
private static void insertSort1(int ns[]){
for(int i = 2; i < ns.length; i++){
if(ns[i] < ns[i - 1]){
ns[0] = ns[i];
ns[i] = ns[i - 1];
int j = i - 2;
for(; (ns[0] < ns[j]); j--){
ns[j + 1] = ns[j];
}
ns[j + 1] = ns[0];
}
}
}
private static void insertSort2(int ns[]){
for(int i = 1; i < ns.length; i++){
if(ns[i] < ns[i - 1]){
int tmp = ns[i];
int j = i - 1;
for(; j >= 0&&(ns[j] > tmp ) ; --j){
ns[j+1] = ns[j];
}
ns[j + 1] = tmp;
}
}
}
private static void bubble(int ns[]){
for(int i = 0; i < ns.length - 1; i++){
for(int j = 1; j < ns.length - i; j++){
if(ns[j - 1] > ns[j]){
int tmp = ns[j];
ns[j] = ns[j - 1];
ns[j - 1] = tmp;
}
}
}
}
private static void shellSor(int ns[]){
int delta[] = {4, 3, 2, 1};
for(int dk : delta){
for(int i = dk ; i < ns.length; i++){
for(int j = i -dk; j>= 0; j -=dk){
if(ns[j] > ns[i]){
int tmp = ns[i];
ns[i] = ns[j];
ns[j] = tmp;
}
}
}
}
}
}