Trying to get this method to add an array and sort the array without using Arrays.sort
I'm making a program that will add values to an array and then sort the values, however, i have to do it under the same method and i cannot use Arrays.sort. I feel like my code makes perfect sense but it isn't changing any part of the array for some reason.
Here's my class file:
Code :
public class IntList
{
int[] list;
private int[] tempArray;
private int numElements = 0;
private int temp=0;
//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size)
{
list = new int[size];
}
//------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//------------------------------------------------------------
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else
{
list[numElements] = value;
numElements++;
}
for (int i = 0 ; i < numElements; i++)
{
if (list[i] > list[i+1])
{
temp = list[i];
list[i] = list[i+1];
list[i] = temp;
}
}
}
//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString()
{
String returnString = "";
for (int i=0; i<numElements; i++)
{
returnString += i + ": " + list[i] + "\n";
}
return returnString;
}
}
Here's the main:
Code :
public class ListTest
{
public static void main(String[] args)
{
IntList myList = new IntList(10);
myList.add(84);
myList.add(27);
myList.add(250);
myList.add(18);
myList.add(94);
myList.add(8);
myList.add(87);
System.out.println(myList);
}
}
Re: Trying to get this method to add an array and sort the array without using Arrays.sort
First of all: Your sort loop doesn't swap anything, so nothing is changed, and the items remain in the order in which they were inserted into the list. (The good news here, is that your results seem to validate the part that inserts new items into the array and keeps count. The bad news is that it doesn't sort the array.)
Secondly: It's very simple: If you are trying to do a bubble sort on the array, then generally speaking, when an array has more than two elements, you can not (that's not) do a bubble sort with one pass through the array. Period.
Don't you have examples in your textbook or class notes or whatever learning material you are using? Don't they use nested loops?
Cheers!
Z
Re: Trying to get this method to add an array and sort the array without using Arrays.sort
Idk what a bubble sort is but i found that all i need is the insertion sort algorithm, which i happened to find online so all is well now, thanks.