数组作业

1.将一个给定的整型数组转置输出,
 例如: 源数组,1 2 3 4 5 6
   转置之后的数组,6 5 4 3 2 1

这是一组从小到大的特殊数组,转置输出后就是从大到小

所以可以用冒泡排序的方法将这个数组按从大到小的顺序排列,然后再遍历输出

源码:

public class test1 {

public static void main(String[] args) {
int[] a = {1,2,3,4,5,6};
int i,j,t;
for(i = 0 ; i < a.length-1;i++)
{
for(j=i+1;j<a.length;j++)
{
if(a[i]<a[j])
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
for(i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}


2.现在有如下的一个数组:
  int[] oldArr = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} ;
 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为:
  int[] newArr = {1,3,4,5,6,6,5,4,7,6,7,5} ;
计算出oldarr数组中非零个数,创建新数组newarr,将oldarr中非零元素传入newarr中
源码:
public class Main {

public static void main(String[] args) {
int[] oldArr = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
int n = 0,m;
int i,j = 0;
for (i=0;i<oldArr.length;i++){
if(oldArr[i]!=0)
{
n++;
}
}
m = n;
int[] newArr =new int[m];

for(i = 0;i < oldArr.length;i++)
{
if(oldArr[i] != 0)
{
newArr[j] = oldArr[i];
j++;
}
}
for(i=0;i<n;i++)
{
System.out.println(newArr[i]);
}
}
}


3.现在给出两个数组:
 数组a:"1,7,9,11,13,15,17,19"
 数组b:"2,4,6,8,10"
      两个数组合并为数组c。
创建新数组长度为ab长度之和,将a,b传入c中
源码:
public class Main {

public static void main(String[] args) {
int[] a = {1,7,9,11,13,15,17,19};
int[] b = {2,4,6,8,10};
int n=a.length+b.length;
int[] c = new int[n];
int i,j;
for(i = 0; i < a.length; i++){
c[i] = a[i];
}
for(j = i; j < n;j++)
{
c[j] = b[j-i];
}
for(i = 0;i < n;i++)
{
System.out.println(c[i]);
}
}
}

猜你喜欢

转载自www.cnblogs.com/JokerCaesar/p/10755672.html