算法2

//求和

public class TestArray4 {

public static void main(String[] args) {

 int[] arr = new int[] {12, 43, 9, 0, -65, -99,100, 9};

//求和

int sum = 0;

for(int i = 0; i 

sum = sum + arr[i];}

System.out.println(sum);

//求平均数

double avg = (double)sum / arr.length;

System.out.println(avg);

} }


public class TestArray5 {

 public static void main(String[] args) {

int x = 5; int y = 8;

// 交换x和y的值

int t;

t = x;

x = y;

 y = t;

System.out.println(x + "," + y);

// 选择排序

int[] arr = new int[] { 46, 53, 21, 18, 39 };

for (int i = 0; i < arr.length - 1; i++) {

 int t = i;// 默认i处是最小的

 for (int j = i + 1; j < arr.length; j++) { // 一旦在i后发现存在比其小的元素,就记录那个元素的下角标 if (arr[t] > arr[j]) {

t = j; } }

 if (t != i) {

 int temp = arr[t];

arr[t] = arr[i];

arr[i] = temp;

 } } System.out.println("排序以后,遍历数组:");

for (int i = 0; i < arr.length; i++) {

System.out.print(arr[i] + "\t"); }*/

 //冒泡排序

 int[] arr = new int[] { 6, 5, 4, 3, 2 }; // 使数组元素从小到大排列

for (int i = 0; i < arr.length - 1; i++) {

 for (int j = 0; j < arr.length - 1 - i; j++) {

if (arr[j] > arr[j + 1]) {

 int temp = arr[j];

 arr[j] = arr[j + 1];

arr[j + 1] = temp;

} } } System.out.println("排序以后,遍历数组:");

 for (int i = 0; i < arr.length; i++) {

System.out.print(arr[i] + "\t"); } } }

你可能感兴趣的:(算法2)