Here is the code (including both classes):
import java.util.Scanner;
import java.util.Random;
public class SortedArray
{
public int [] myNums;
public int sizeOfArray;
private int userInput;
public Sort sortedArray;
public Scanner input = new Scanner(System.in);
public void sortedArray()
{
System.out.println("Enter the number of values to put in the array:");
int userInput = input.nextInt();
myNums = new int [userInput];
sizeOfArray = userInput;
for(int i=0;i<userInput;i++)
{
Random randomNum = new Random();
myNums[i] = randomNum.nextInt(100)+1;
}
for(int i=0;i<userInput;i++)
{
System.out.println(myNums[i]);
}
sortedArray = new Sort(myNums, sizeOfArray);
sortedArray.publicdisplay();
}
}
*******************************************************************************
public class Sort
{
public int[] array;
public int sizeOfArray;
public Sort(int[] oldArray, int sizeOfOldArray)
{
sizeOfArray = sizeOfOldArray;
for( int i = 0; i < sizeOfArray; i++) {
array[i] = oldArray[i];
}
sort();
}
public void publicdisplay()
{
for ( int i = 0; i < sizeOfArray; i++){
System.out.println(array[i]);
}
}
private void sort()
{
for (int i = 0; i < sizeOfArray; i++)
{
for (int j = 0; j < sizeOfArray; i++)
{
if (array[j] < array[i])
{
swap(i,j);
}
}
}
}
private void swap(int x, int y)
{
int temp = 100;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}
The program compiles correctly, however when I run the program and enter the number of values to put in the array, I get the following error:
java.lang.NullPointerException
at Sort.<init>(Sort.java:17)
at SortedArray.sortedArray(SortedArray.java:32)
It generates the array but does not sort it. I would appreciate any help, thanks.
for (int j = 0; j < sizeOfArray; i++)
tofor (int j = i+1; j < sizeOfArray; j++)
. However, I suggest visiting sorting-algorithms.com/shell-sort instead. – Edward Falk Jun 14 '13 at 0:56