Selection Sort not sorting Java - java

I am working on a selection sort in Java. It will prompt a user to enter in 10 names and then sort them alphabetically. It is sorting some of them but not completely and cannot figure out why it is sorting some values and not others. I believe I have implemented the sort and swap correctly but I feel as though I am missing something. Any help is appreciated as always.
import java.util.*;
public class sortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}

You are doing your swap too early. You need to wait until the smallest has been determined before swapping. You are swapping whenever you detect a smaller one.
public static void sortNames(String sortArray[]) {
for (int i = 0; i < sortArray.length; i++) {
int smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
// Move this.
//if (smallindex != i)
// swap(sortArray, smallindex, i);
}
}
// To here.
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
private void test() {
String[] names = {"C", "B", "A", "9"};
System.out.println(Arrays.toString(names));
sortNames(names);
System.out.println(Arrays.toString(names));
}

use below changes in your program.
import java.util.*;
public class SortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
//if (smallindex != i) No need here
//swap(sortArray, smallindex, i);
}
}
//place your swaping code here
if (smallindex != i)
swap(sortArray, smallindex, i);
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
after making these changes your program works. your code not works properly because you perform swap early.

Related

How does the scope of this private method work?

My question is: how can I see the Tuple result in the process method if it was created in the check method? How am I able to use it there, if it was created in a private method?
public class Problem13 {
private Tuple<Integer> costs;
private Tuple<String> names;
private Tuple<Integer> result;
private int budget;
private int minDelta, minCost, totalCost;
public void process(String fileName) {
if (!read(fileName))
return;
if (budget >= totalCost) {
System.out.println("You can buy all items");
return;
}
if (budget < minCost) {
System.out.println("You cannot buy items");
return;
}
minDelta = -1;
int n = costs.getLength();
Set<Integer> interval = new IntegerInterval(0, n - 1);
for (int k = n - 1; k > 0; --k) {
Combinations<Integer> combinations = new Combinations<Integer>(interval, k);
combinations.produce((tuple) -> !check(tuple));
if (minDelta == 0)
break;
}
if (result == null)
System.out.println("No solution found");
else {
int k = result.getLength();
for (int j = 0; j < k; ++j)
System.out.printf("%s ", names.get(result.get(j)));
System.out.printf("(%d)\n", minDelta);
}
}
public static void main(String[] args) {
new Problem13().process("data/input13.txt");
}
private boolean check(Tuple<Integer> tuple) {
int k = tuple.getLength();
int currentCost = 0;
for (int i = 0; i < k; ++i) {
int j = tuple.get(i);
currentCost += costs.get(j);
if (currentCost > budget)
return false;
}
int d = budget - currentCost;
if (minDelta < 0 || d < minDelta) {
minDelta = d;
result = new ArrayTuple<>(k);
for (int i = 0; i < k; ++i)
result.set(i, tuple.get(i));
}
return minDelta == 0;
}
private means private to the class. So Problem13 can see anything defined in that class, whether private, public, protected or package private.
Also, the access modifier of the method only affects who can call it, not where the results can be seen. For instance, if result was defined as a public field, any class (not just Problem13) could see it.
You can find many good breakdowns of access modifiers out there on the Interwebs. Here's one.

Try to fill ArrayList from object with String and int.Is not working

I have class Book with three fields - name, author and isbn
I`m trying to insert the fields in ArrayList and to print:
book1, author1, isbn
book2, author2, isbn2
and... to 10
code:
public class InsertBooks {
private static ArrayList<String> booksNames = new ArrayList<>();
private static ArrayList<String> booksAuthors = new ArrayList<>();
private static ArrayList<Integer> booksIsbn = new ArrayList<>();
private static ArrayList<Book> books = new ArrayList<>();
// adding books in ArrayList booksNames
private static void addBooksNames() {
for (int i = 0; i < 10; i++) {
booksNames.add("Book" + i);
}
}
// adding author in ArrayList booksAuthors
private static void addBooksAuthor() {
for (int i = 0; i < 10; i++) {
booksAuthors.add("Author" + i);
}
}
// adding author in ArrayList booksAuthors
private static void addBooksIsbn() {
for (int i = 0; i < 10; i++) {
booksIsbn.add(Integer.valueOf("isbn" + i));
}
}
public static void fillArrayListOfBooks() {
for (int i = 0; i < 10; i++) {
books.add(new Book((addBooksNames(), addBooksAuthor(), addBooksIsbn()));
}
}
}
You want to call all your add* functions first. Then in the loop of fillArrayListOfBooks() use those values.
void fillArrayListOfBooks()
{
addBooksNames();
addBooksAuthor();
addBooksIsbn();
for (int i = 0; i < 10; i++) {
dbooks.add(new Book(booksNames.get(i), booksAuthors.get(i), booksIsbn.get(i)));
}
}
You could easily get rid of those lists (unless you need them later):
void fillArrayListOfBooks()
{
for (int i = 0; i < 10; i++) {
dbooks.add(new Book("Book" + i, "Author" + i, "isbn" + i));
}
}

How to fix java error?

So I have to create a program where I use polymorphism and inheritance to create arrows that point left and arrow and I did that. however, when I created my main class and try to invoke the methods, say for example "LeftArrow.drawHere" to draw the arrow i get errors saying I cannot make a static reference to the non static field "drawHere() from the class LeftArrow". I was wondering then if I can't do that how can I design my main method so it draws the arrows?
here is my code, note that there are several classes but I will post all of them here.
import java.util.Scanner;
public class LeftArrow extends ShapeBasic
{
private int tail, width;
private static int inside;
public LeftArrow()
{
super();
tail = 0;
width = 0;
}
public LeftArrow(int noff, int ntail, int nwidth)
{
super(noff);
tail = ntail;
setWidth(nwidth);
}
public void setTail(int ntail)
{
tail = ntail;
}
public int getTail()
{
return tail;
}
public void setWidth(int nwidth)
{
if (nwidth % 2 == 1)
{
width = nwidth;
}
else
{
System.out.println(" Width must be odd");
System.out.println("Enter a new width");
Scanner key = new Scanner(System.in);
int wid = key.nextInt();
setWidth(wid);
}
}
public int getWidth()
{
return width;
}
public void drawHere()
{
drawTriangle();
drawTail();
drawBTriangle();
//System.out.println();
}
public void drawTriangle()
{
inside = 1;
int split = (width/2);
skipSpaces(getOffset());
System.out.println('*');
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() - (inside + 1));
System.out.print('*');
skipSpaces(inside);
System.out.print('*');
inside = inside + 2;
System.out.println();
}
}
public void drawTail()
{
skipSpaces(getOffset() - getInside() - 1);
System.out.print('*');
skipSpaces(getInside());
for (int count = 0; count < tail ; count++)
{
System.out.print('*');
}
}
public void drawBTriangle()
{
int inside = getInside();
int split = (width/2);
System.out.println();
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() - (inside - 1));
System.out.print('*');
inside = inside - 2;
skipSpaces(inside);
System.out.print('*');
System.out.println();
}
skipSpaces(getOffset());
System.out.print('*');
}
public int getInside()
{
return inside;
}
private static void skipSpaces(int number)
{
for (int count = 0; count < number; count++)
System.out.print(' ');
}
#Override
public void setOffset(int noff) {
// TODO Auto-generated method stub
}
#Override
public int getOffset() {
// TODO Auto-generated method stub
return 0;
}
}
import java.util.Scanner;
public class RightArrow extends ShapeBasic
{
private int tail, width;
private static int inside;
public RightArrow()
{
super();
tail = 0;
width = 0;
}
public RightArrow(int noff, int ntail, int nwidth)
{
super(noff);
tail = ntail;
setWidth(nwidth); // must be odd
}
public void setTail(int ntail)
{
tail = ntail;
}
public int getTail()
{
return tail;
}
public void setWidth(int nwidth)
{
if (nwidth % 2 == 1)
{
width = nwidth;
}
else
{
System.out.println(" Width must be odd");
System.out.println("Enter a new width");
Scanner key = new Scanner(System.in);
int wid = key.nextInt();
setWidth(wid);
}
}
public int getWidth()
{
return width;
}
public void drawHere()
{
drawTriangle();
drawTail();
drawBTriangle();
System.out.println();
}
public void drawTail()
{
skipSpaces(getOffset() + 1);
for (int count = 0; count < tail ; count++)
{
System.out.print('*');
}
skipSpaces(getInside());
System.out.print('*'); // fix
}
public void drawTriangle()
{
inside = 1;
int split = (width/2);
skipSpaces(getOffset() + tail);
System.out.println('*');
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() + tail);
System.out.print('*');
skipSpaces(inside);
System.out.print('*');
inside = inside + 2;
System.out.println();
}
}
public void drawBTriangle()
{
int inside = getInside();
int split = (width/2);
System.out.println();
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() + tail);
System.out.print('*');
inside = inside - 2;
skipSpaces(inside);
System.out.print('*');
System.out.println();
}
skipSpaces(getOffset() + tail);
System.out.print('*');
}
public int getInside()
{
return inside;
}
private static void skipSpaces(int number)
{
for (int count = 0; count < number; count++)
System.out.print(' ');
}
}
public abstract class ShapeBase implements ShapeInterface {
private int offset;
public abstract void drawHere();
public void drawAt(int lineNumber) {
for (int count = 0; count < lineNumber; count++)
System.out.println();
drawHere();
}
}
public class ShapeBasic implements ShapeInterface
{
private int offset;
public ShapeBasic()
{
offset = 0;
}
public ShapeBasic( int noff)
{
offset = noff;
}
public void setOffset(int noff)
{
offset = noff;
}
public int getOffset()
{
return offset;
}
public void drawAt(int linnumber)
{
for (int count = 0; count < linnumber; count++)
System.out.println();
drawHere();
}
public void drawHere()
{
for (int count = 0; count < offset; count++)
System.out.print(' ');
System.out.println('*');
}
}
public interface ShapeInterface
{
public void setOffset(int noff); // set how many space from left
public int getOffset(); // returns offset
public void drawAt(int linnumber); // moves down equal to line number Ex. 5 = 5 down
public void drawHere(); // draws shape after moving left equal to offset
}
I'd ask to see your main method, but I don't have the reputation.
At a guess, I'd say maybe you are not actually instantiating objects of these classes in your main method, but trying to call the methods from them. If, for instance, you do this:
LeftArrow lArrow = new LeftArrow();
lArrow.drawHere();
it should work.
The method drawHere is declared as non-static. Instead of LeftArrow.drawHere() you should call
LeftArrow left = new LefArrow(a, b, c);
left.drawHere();
main is static. It needs to create instances of LeftArrow before it can use them. Something like this:
LeftArrow myArrow = new LeftArrow();
myArrow.drawHere();

Java Why am I getting a NullPointerException while instantiating my array

I am new to programming and don't get why the program gives me a run time error for NullPointerException when I have tried initializing n, numInt, and arrayMenu. None of which seem to work. The program's job is to gather a set of random integers to store in an array and allow the user to pick which sort to choose from. Thanks for reading.
import java.util.Scanner;
import java.util.Random;
public class VariousSortsHS
{
private static int[] arrayMenu;
private static Random generator;
/**
* Constructor for objects of class VariousSortsHS.
*/
public VariousSortsHS(int n) //The error starts here
{
arrayMenu = new int[n]; //I don't get why it says null in the array when
//i am initializing the length of the array to n
/*Assigns a random number between 0 too 100.*/
for(int i = 0; i < n; i++)
{
int temp = generator.nextInt(100);
arrayMenu[n] = temp;
}
}
/**
* Selection Sort method.
*/
public static void selection(int n)
{
for(int i = 0; i < arrayMenu.length - 1; i++)
{
int minPos = i;
for(int j = i + 1; j < arrayMenu.length; j++)
{
if(arrayMenu[j] < arrayMenu[minPos]) minPos = j;
}
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[minPos];
arrayMenu[minPos] = temp;
System.out.print(temp + " ");
}
}
/**
* Insertion Sort method.
*/
public static void insertion(int n)
{
for(int i = 1; i < arrayMenu.length; i++)
{
int next = arrayMenu[i];
int j = i;
while(j > 0 && arrayMenu[j - 1] > next)
{
arrayMenu[j] = arrayMenu[j - 1];
j--;
}
arrayMenu[j] = next;
System.out.print(next + " ");
}
}
/**
* Quick Sort method.
*/
public static void quick(int n)
{
int pivot = arrayMenu[0];
int i = 0 - 1;
int j = n + 1;
while(i < j)
{
i++; while(arrayMenu[i] < pivot) i++;
j++; while(arrayMenu[j] > pivot) j++;
if(i < j)
{
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[j];
arrayMenu[j] = temp;
System.out.print(temp + " ");
}
}
}
/**
* Main method that allows user to input data.
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Do you wish to sort random integers? (Yes or No) ");
String answer = in.next();
String answer2 = answer.toLowerCase();
do
{
/*Prompts for array length.*/
System.out.println("How many random integers do you wish to sort?");
int numInt = in.nextInt();
/*Promps for sort selection choice.*/
System.out.println("Select a sort to use: \n\t1)Selection\n\t2)Insertion\n\t3)Quick");
String sort = in.next();
String sort2 = sort.toLowerCase();
if(sort2.equals("selection"))
{
selection(numInt);
}
else if(sort2.equals("insertion"))
{
insertion(numInt);
}
else if(sort2.equals("quick"))
{
quick(numInt);
}
else
{
System.out.println("You have entered the wrong input.");
}
} while(!answer2.equals("no"));
}
}
Everything in your code is static. This means the constructor you wrote is never called, and the array has never been changed from its default value, null. Consider changing your constructor code to a static initialization block instead.
generator is never set to anything, so it's null too and you can't call nextInt on it
initializing the array is setting arrayMenu[n] instead of arrayMenu[i]
When you call insertion(numInt);, method public static void insertion(int n) is called and then you are trying to do the for-loop like this for(int i = 1; i < arrayMenu.length; i++)
However, arrayMenu was not initialized, it is null. When you try to call a length, on null, you get NullPointerException.
You need to add a static constructor and initialize the size using a static int
//set parameter = n
public static int parameter;
static
{
arrayMenu = new int[parameter];
}

Java - swap arraylist index

I made a map by arraylist, and trying to swap the index(not the value) of arraylist.
For example, the swapRow(1,2) changes the position of row 1 and 2.
This works at the first time, but if I do it again, an error comes out.(Same problem with the swapCol() part.)
Stuck in this problem and need help...
In addition, can anyone help me out making the swapValue() method.
Changing the value is simple, though I also want to move the index, not the value.
import java.text.DecimalFormat;
import java.util.ArrayList;
public class IntMap {
class Data {
private int data_;
public Data(int data)
{
setData(data);
}
public void setData(int data)
{
if(data<0)data=0;
if(data>99)data=99;
data_=data;
}
public int getData()
{
return data_;
}
}
class Index {
private int index_;
public Index(int index)
{
setIndex(index);
}
public void setIndex(int index)
{
if(index < 0) index=0;
index_=index;
}
public int getIndex()
{
return index_;
}
}
private ArrayList<ArrayList<Data>> datas_;
private ArrayList<Index> cols_;
private ArrayList<Index> rows_;
public IntMap(int rowCount, int colCount)
{
if(rowCount < 0) rowCount = 1;
if(rowCount < 0) colCount = 1;
cols_ = new ArrayList<Index>();
rows_ = new ArrayList<Index>();
datas_ = new ArrayList<ArrayList<Data>>();
for(int i=0 ; i<rowCount ; ++i) rows_.add(new Index(i));
for(int i=0 ; i<colCount ; ++i) cols_.add(new Index(i));
for(int i=0 ; i< rowCount ; ++i)
{
ArrayList<Data> temp = new ArrayList<Data>();
datas_.add(temp);
for(int j=0 ; j<colCount ; ++j)
{
temp.add(new Data(0));
}
}
}
public int getValue(int row, int col)
{
int rIndex = getRowIndex(row);
int cIndex = getColIndex(col);
return datas_.get(rIndex).get(cIndex).getData();
}
public void setValue(int row, int col, int value)
{
int rIndex = getRowIndex(row);
int cIndex = getColIndex(col);
datas_.get(rIndex).get(cIndex).setData(value);
}
public void setRandomValue()
{
for(int row=0 ; row < datas_.size() ; ++row)
{
ArrayList<Data> temp = datas_.get(row);
for(int col=0; col <temp.size() ; ++col)
{
Data data = temp.get(col);
data.setData((int)(Math.random()*100));
}
}
}
public void log()
{
DecimalFormat df = new DecimalFormat("00");
for(int row=0; row<rows_.size(); ++row)
{
for(int col=0; col<cols_.size(); ++col)
{
int value = getValue(row, col);
System.out.print(df.format(value));
if(col<cols_.size()-1)
System.out.print(", ");
}
System.out.println();
}
System.out.println();
}
private int getColIndex(int col)
{
if(col <0 || col>=cols_.size())
{
System.out.println("[error][IntMap][getColIndex] - col is"+col);
return 0;
}
for(int i =0; i<cols_.size(); ++i)
{
if(cols_.get(i).getIndex()==col)
return i;
}
System.out.println("[error][IntMap][getColIndex] - unknown error");
return 0;
}
private int getRowIndex(int row)
{
if(row <0 || row>=rows_.size())
{
System.out.println("[error][IntMap][getRowIndex] - row is"+row);
return 0;
}
for(int i =0; i<rows_.size(); ++i)
{
if(rows_.get(i).getIndex()==row)
return i;
}
System.out.println("[error][IntMap][getRowIndex] - unknown error");
return 0;
}
public void swapValue(int a, int b, int c, int d)
{
//
}
public void swapCol(int a, int b)
{
int col1=a;
int col2=b;
int t=a;
cols_.get(col1).setIndex(col2);
cols_.get(col2).setIndex(t);
}
public void swapRow(int a, int b)
{
int t=a;
rows_.get(a).setIndex(b);
rows_.get(b).setIndex(t);
}
public static void main(String[] args)
{
System.out.println("start!");
IntMap map =new IntMap(3,4);
System.out.println("Init map 3x4");
map.log();
System.out.println("random map");
map.setRandomValue();
map.log();
System.out.print("get map[0][1]= ");
System.out.println(map.getValue(0,1));
System.out.println("set map[2][1]=50");
map.setValue(2, 1 ,50);
map.log();
System.out.println("swap(0,1 <-> 2,1)");
map.swapValue(0,1,2,1);
map.log();
System.out.println("swapRow(0 <-> 2)");
map.swapRow(0,2);
map.log();
System.out.println("swapRow(1 <-> 2)");
map.swapRow(1,2);
map.log();
System.out.println("swapCol(0 <-> 3)");
map.swapCol(0,3);
map.log();
}
}
I think you got confused the index of rows_ arrayList and your Index type. your swapRow(a,b) should check rows_ list and find out the element (Index Object) .getIndex = a and b, then swap the two Index elements, not just like what you did in your method. If you change the method into followings, it should work. you could do some error handling, e.g. what happend parameter a or b invalid. I just set themt to 0.
public void swapRow(int a, int b) {
int ai = 0, bi = 0;
for (final Index i : rows_) {
if (i.getIndex() == a) {
ai = rows_.indexOf(i);
}
if (i.getIndex() == b) {
bi = rows_.indexOf(i);
}
}
final Index aidx = rows_.get(ai);
rows_.set(ai, rows_.get(bi));
rows_.set(bi, aidx);
}
and, i don't know your exact requirment. but from the design point of view, there might be room to improve.

Categories