用JAVA编写一个程序,对数组中每个元素赋值,然后按逆序输出。

如题所述

public class ArraySort {

/**
* @param args
*/
public static void main(String[] args) {
int[] a = { 12, 2, 45, 23, 9, 88, 33, 23, 22, 5, 4, 4, 5, 1, 9, 7, 2,
7, 8, 0 };
ArraySort.bubbleSort(a);
}

/**
* 冒泡排序。从大到小排序。<br>
*
* @param source
* @return
*/
public static int[] bubbleSort(int[] source) {
boolean isSort = false; // 是否排序

for (int i = 1; i < source.length; i++) {
isSort = false; // 在每次排序前都初始化为false
for (int j = 0; j < source.length - i; j++) {
if (source[j] < source[j + 1]) {
int temp = source[j];
source[j] = source[j + 1];
source[j + 1] = temp;

isSort = true; // 为TRUE表明此次循环(外层循环)有排序。
}
}

if (!isSort)
break; // 如果没有排序,说明数据已经排序完毕。
// 输出每个子循环排序后的数组中的元素
printArray(source, i);
}
return source;
}

/**
* 循环输出数组中的元素。
*
* @param a
* @param idx
* ,第一层循环的index
*/
public static void printArray(int[] a,int idx) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + (i != a.length-1?",":""));
}
System.out.println("--idx:" + idx);
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-03-14
import java.io.*;
public class test {
public static void main(String args[]) throws IOException{
int len;
BufferedReader inStr;
System.out.println("请输入要输入数组的元素个数");
inStr = new BufferedReader(new InputStreamReader(System.in));
len=Integer.parseInt(inStr.readLine());
String strArray[] = new String[len];
for(int i=0; i<len; i++){
System.out.println("请输入第"+(i+1)+"个元素");
inStr = new BufferedReader(new InputStreamReader(System.in));
strArray[i]=inStr.readLine();
}
System.out.print("你输入元素倒序排晚是:");
for(int k = len-1; k>=0; k--){
System.out.print(strArray[k]+",");
}
}
}
相似回答