找出数组的中间值

// A2.java

public class A2 {

    
private final static int N = 10;

    
public static void main(String[] args) {
        
int a[] = new int[N];
        createArray(a);
        printArray(a);

        
int b[] = copyArray(a);
        sortArray(b);
        printArray(b);

        System.out.println(exec(a));

    }

    
public static int exec(int a[]) {
        
int result = 0;
        
// 取中间
        if (N % 2 == 1) {
            
for (int i = 0; i <= N / 2; i++) {
                
for (int j = 0; j < (N - 1- i; j++) {
                    
if (a[j] > a[j + 1]) {
                        a[j] 
= a[j + 1+ 0 * (a[j + 1= a[j]);
                    }
                }
            }
            result 
= a[N / 2];
        }
// 取中间两数平均值
        else {
            
for (int i = 0; i <= N / 2; i++) {
                
for (int j = 0; j < (N - 1- i; j++) {
                    
if (a[j] > a[j + 1]) {
                        a[j] 
= a[j + 1+ 0 * (a[j + 1= a[j]);
                    }
                }
            }
            result 
= (a[N / 2 - 1+ a[N / 2]) / 2;
        }
        
return result;
    }

    
public static void createArray(int a[]) {
        
for (int i = 0; i < N; i++) {
            a[i] 
= (int) (Math.random() * 50);
        }
    }

    
public static void printArray(int a[]) {
        
for (int i = 0; i < N; i++) {
            System.out.print(a[i] 
+ " ");
        }
        System.out.println();
    }

    
public static int[] copyArray(int a[]) {
        
int b[] = new int[N];
        
for (int i = 0; i < N; i++) {
            b[i] 
= a[i];
        }
        
return b;
    }

    
public static void sortArray(int a[]) {
        
for (int i = 0; i <= N - 1; i++) {
            
for (int j = 0; j < (N - 1- i; j++) {
                
if (a[j] > a[j + 1]) {
                    a[j] 
= a[j + 1+ 0 * (a[j + 1= a[j]);
                }
            }
        }
    }
}

 

47 9 2 9 21 37 42 2 18 6
2 2 6 9 9 18 21 37 42 47
13

11 28 43 28 40 12 45 28 38 18
11 12 18 28 28 28 38 40 43 45
28

posted on 2009-11-21 14:44  我为Java而努力  阅读(2282)  评论(0)    收藏  举报

导航