Java学习~数组输出大小值及排序方法

数组输出大小值

for循环遍历

package example;

public class ArrayMaxMin {
      public static void main(String[] args) {
    	  int max,min,i;
    	  int A[]= {27,86,132,55,34,13};
    	  max = min = A[0];
    	  System.out.print("数组A的元素包括:");
    	  for(i=1;imax)
    			  max=A[i];
    		  if(A[i]

 补充数组排序

1.冒泡排序

public void bubbleSort(int a[]) { 
 
    int n = a.length; 
 
    for (int i = 0; i < n - 1; i++) { 
 
      for (int j = 0; j < n - 1; j++) { 
 
        if (a[j] > a[j + 1]) { 
 
          int temp = a[j]; 
 
          a[j] = a[j + 1]; 
 
          a[j + 1] = temp; 
 
        } 
 
      } 
 
    } 
 
} 

2.选择排序

public void selectSort(int a[]) { 
 
    for (int n = a.length; n > 1; n--) { 
 
      int i = max(a, n); 
 
      int temp = a[i]; 
 
      a[i] = a[n - 1]; 
 
      a[n - 1] = temp; 
 
    } 
 
} 

3.插入排序

public void insertSort(int a[]) { 
 
    int n = a.length; 
 
    for (int i = 1; i < n; i++) { //将a[i]插入a[0:i-1] 
 
      int t = a[i]; 
 
      int j; 
 
      for (j = i - 1; j >= 0 && t < a[j]; j--) { 
 
        a[j + 1] = a[j]; 
 
      } 
 
      a[j + 1] = t; 
 
    } 
 
}

4.设置两层循环

for(int i=0;iarrayOfInts[j]) 
 
      { 
 
        a=arrayOfInts[i]; 
 
        arrayOfInts[i]=arrayOfInts[j]; 
 
        arrayOfInts[j]=a; 
 
      } 
 
    } 
 
} 

5.还有一种方法就是用Arrays.sort()方法:

//导入包 
 
import java.util.Arrays;
 
 
 
public class Two3{ 
 
 
 
    public static void main(String[]args) 
 
    { 
 
      int[]arrayOfInts={32,87,3,589,12,7076,2000,8,622,127}; 
 
 
 
      Arrays.sort(arrayOfInts); 
 
 
 
      for(int i=0;i

 

你可能感兴趣的:(java)