数组排序
数组排序是指将一个杂乱的数组按照顺序进行码放,但是对于数组排序通过基础模式实现。
例子:数组升序排序:int A []=new int[] {8,9,0,2,3,5,10,7,6,1};
方法1:
public class Array{
public static void main (String args[]){
int A []=new int[] {8,9,0,2,3,5,10,7,6,1};
for (int y=0;y<A.length ;y++ ) {
for (int x=0;x<A.length-y-1;x++){
if (A[x]>A[x+1]){
int b=A[x];
A[x]=A[x+1];
A[x+1]=b;
}
}
}
print(A);
}
//要求接收一个int型地数组,定义print方法
public static void print(int b []){
for (int y=0;y<b.length ;y++ ){
System.out.print(b[y]+"、");
}
}
}
输出结果:0、1、2、3、5、6、7、8、9、10、
方法2:通过定义一个工具类实现
如果类中无属性,则需要添加static修饰,避免实例化。
class paixu{//定义排序工具类
public static void sort(int A[]){ //定义方法,加static不使用实例化,因为类中无属性
for (int y=0;y<A.length ;y++ ) { //获取数组值
for (int x=0;x<A.length-y-1;x++){ //排序循环
if (A[x]>A[x+1]){
int b=A[x];
A[x]=A[x+1];
A[x+1]=b;
}
}
}
}
//要求接收一个int型地数组,定义print方法
public static void print(int b []){
for (int y=0;y<b.length ;y++ ){
System.out.print(b[y]+"、");
}
}
}
public class Array{
public static void main (String args[]){
int A []=new int[] {8,9,0,2,3,5,10,7,6,1};
paixu.sort(A);
paixu.print(A);
}
}
输出结果:0、1、2、3、5、6、7、8、9、10、
数组转置
数组反转操作指的是前后转置处理,即首位交换,例如现有一个数组内容为:1、2、3、4、4、5、6、7、8、9,使其反转。
·方法1,定义一个数组,然后按照逆序方式保存。
class A{
//定义print方法,打印输出数组
public static void print(int b []){
for (int x=0;x<b.length ;x++ ){
System.out.print(b[x]+"、");
}
}
}
public class Array{
public static void main (String args[]){
int a []=new int[] {1,2,3,4,5,6,7,8,9};
int b []=new int [a.length];
int foot=b.length-1;
for (int x=0;x<a.length ;x++ )
{
b[foot--]=a[x];
}
a=b;
A.print(a);
}
}
输出结果:9、8、7、6、5、4、3、2、1、
内存分析可知在转置过程中会产生垃圾。
·方法2:如果实现这种转置就要确定数组转换次数,次数计算:数组长度/2,不需要考虑数组长度奇偶。
class A{//定义排序工具类
public static void C(int a[]){
int c = a.length/2;
int head=0;
int tail=a.length-1;
for (int x=0;x<c ;x++){
int b=a[head];
a [head]=a [tail];
a [tail]=b;
head++;
tail--;
}
}
//定义print方法,打印输出数组
public static void print(int b []){
for (int x=0;x<b.length ;x++ ){
System.out.print(b[x]+"、");
}
}
}
public class Array{
public static void main (String args[]){
int a []=new int[] {1,2,3,4,5,6,7,8,9};//定义数组a
A.C(a);
A.print(a);
}
}
输出结果:9、8、7、6、5、4、3、2、1、