国产成人AV一区二区三区在线_国产成人精品无码免费看_国产成人无码无卡在线观看_国产精品成人A区在线观看_国产日韩精品欧美一区_国产亚洲精品自在久久蜜TV_久草热久草热线频97精品_久久久噜噜噜久久中文福利_久久婷婷五月综合色国产免费观看_日日狠狠久久偷偷色综合0,九一桃色在线观看,久久97精品久久久久久久不卡,国产成人精品亚洲精品

java有序順序表中按順序插入數(shù)字

訪客2025-01-21 21:34:351

運行結(jié)果為3 5 7 8 9,,總是沒有1,如果我想插入10程序就會出錯,,希望大佬能指導(dǎo)一哈!public class sj1<T> {final int Size=10;private T[] Array;private int length;@SuppressWarnings("unchecked")public sj1() {length=0;Array=(T[])new Object[Size];System.out.println("初始化成功!");}public boolean add(T obj,int pos) {if(pos<1 || pos>length+1) {System.out.println("pos值不合法");return false;}if(length==Array.length) {@SuppressWarnings("unchecked")T[] p=(T[]) new Object[length*2];for(int i=0;i<length;i++)p[i]=Array[i];Array=p;}for(int i=length;i>=pos;i--)Array[i]=Array[i-1];Array[pos-1]=obj;length++;return true;}@SuppressWarnings("unchecked")public boolean cha(T obj) {if(length==Array.length) {T[] p=(T[]) new Object[length*2];for(int i=0;i<length;i++)p[i]=Array[i];Array=p;} int i,j,n;for(i=1,j=0;i<Array.length;i++,j++){if( (int)obj < (int)Array[i]){Array[j+1]=Array[i];Array[j++]=obj;break;} Array[j]=Array[i];}for( n=i+1,j=j+1;n<Array.length;n++,j++) Array[j]=Array[n];return true;}public void nextOrder() {for(int i=0;i<length;i++)System.out.println(Array[i]);}public static void main(String[] args) {// TODO Auto-generated method stubsj1<Integer> va=new sj1<Integer>();int arr[]= {1,3,5,7,9};for(int i=0;i<arr.length;i++)va.add(arr[i],i+1);System.out.println("插入前的順序為:");va.nextOrder();System.out.println("插入是否成功:"+va.cha(8));System.out.println("插入后的順序為:");va.nextOrder();}

你的插入算法有問題的,,以下是我改寫的,,經(jīng)測試沒有問題了

public boolean cha(T obj) {if(length==Array.length) {T[] p=(T[]) new Object[length*2];for(int i=0; i<length; i++)p[i]=Array[i];Array=p;}int i,j;for(i = 0; i < length; i++){if((int)Array[i] >= (int)obj) //找到插入位置{for(j = length; j > i; j--) //當前開始數(shù)據(jù)右移一個Array[j] = Array[j - 1];Array[i] = obj; //插入break;}}if((int)obj > (int)Array[length-1])Array[length] = obj; //插入到最后length++;return true;}

文章評論