插入基本排序数组 [英] inserting in basic sorted array
本文介绍了插入基本排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hello I have implemented this basic program which should sort out the strings that are inserted however it somehow is failing to insert the strings . For example if I implement :
testsort t = new testsort();
t.i("abc");
t.i("aab");
Can anybody see the error and help me fix this error please ?
Thank you
Here is the code :
public class testsort {
private int length;
String[] data;
public testsort()
{
length = 0;
}
public void i(String value)
{
data[length] = value;
SetSorted(data);
length++;
}
public void SetSorted(String data[])
{
for(int i = data.length-1; i >= 0; i--)
{
for(int j = 0; j < i; j++) {
if(data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
for(int i = 0; i < data.length; i++)
{
System.out.print(data[i] +" ");
}
}
}
推荐答案
您没有在testsort
的构造函数中分配数据
,所以它总是为空。因此,任何试图访问数据
的调用,如data [length] = value
,都将失败。 />
您需要确保数据
有空间容纳您计划添加的元素数量,或者让它动态调整大小添加新项目。
希望这会有所帮助,
Fredrik
You're not allocatingdata
in the constructor oftestsort
, so it's always null. Because of this, any call trying to accessdata
, likedata[length] = value
, will fail.
You need to make suredata
has room for the number of elements you plan to add, or have it dynamically resize as new items are added.
Hope this helps,
Fredrik
这篇关于插入基本排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文