平时用php把人都用懒了,用java写东西瞬间感觉好别扭,不过最后还是写下来了,
以后还是要多用java写代码啊
首先我来解释一下这个算法:
比如说数列b1,b2,b3,b4 通过比较最少的次数来找出最小的值:
我们就可以比较b1,b2一次,比较b3,b4一次再将得出的两个较小值做比较就得出来了
代码如下
package Arithmetic;
import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
public class test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println(Prime.prime_num(101, 200));
int arr[] = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int i = 0;
int[] a = null;
int size = 0;
int[] min = null;
min = new int[1];
try {
size = Integer.parseInt(br.readLine());
a = new int[size];
} catch (NumberFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(i = 0; i < size; i++){
try {
a[i] = Integer.parseInt(br.readLine());
} catch (NumberFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// System.out.println(Arrays.binarySearch(a, 2));
System.out.println("交换次数===>" + test.pcount(a));
}
//返回为指定数组排序所经过的最少交换的次数
public static int pcount(int[] b){
int i = 0;
int j = 0;
int tmp_index = 0;
int j_count = 0;
int tmp = 0;
int[] min = null;
min = new int[1];
int[] copy = null;
for(i = 0; i < b.length; i++){
copy = null;
copy = new int[b.length-i];
for(j = 0; j < b.length-i; j++){
copy[j] = b[i+j];
}
System.out.println("copy.length=====" + copy.length);
min = test.min_var(copy);
if(min[0] != b[i]){
tmp_index = test.ArrSearch(b, min[0]);
System.out.println("min====>" + min[0]);
System.out.println("index====>" + tmp_index);
System.out.println(test.ArrSearch(b, 4));
tmp = b[i];
b[i] = min[0];
b[tmp_index] = tmp;
j_count++;
}
}
return j_count;
}
//返回给定的数组中的最小值(由于用到了迭代所以以数组形式返回)
public static int[] min_var(int[] c){
int[] d = new int[1];
int[] f = null;
int i = 0;
int j = 0;
int count = 0;
int max_count = (int)((c.length+1)/2) ;
int[] e = new int[max_count];
for(i = 0; i < c.length; i = i+2){
if(i+1 < c.length){
e[j] = (c[i] < c[i+1] ? c[i]:c[i+1]);
count++;
}
else{
e[j] = c[i];
}
j++;
}
if(e.length > 1){
d = test.min_var(e);
}
else{
d = e;
}
System.out.println(" 比较次数=====>" + count);
return d;
}
//根据值查找数组中的索引
public static int ArrSearch(int[] s, int v){
int i = 0;
int result = -1;
for(i = 0; i < s.length; i++){
if(s[i] == v){
result = i;
break;
}
}
return result;
}
}