This is a expense sorter which I need to make for my class. I need a binary search method but don't know where to start. I know that binary searching works from the middle of a sorted array but the explanations from websites such as Wikipedia are very confusing.
The code consists of two sorting methods. Linear and selection sort. I have a user input in the variable size which tells the program about the size of the array.Can someone give me an example and explain it in the code using comments.
I want a user to give an input which will be the number that they are looking for. If the number is 57 then the array will scan the middle of the array and determine the number. lets say that number is 56. 56 is less than 57 so it will count upwards from that point until it finds that number
package project;
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class project {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Size;
int order;
System.out.println("Put in the amount of expenses you have");
Size = sc.nextInt();
System.out.println("put in all your expenses");
int userInput[] = new int[Size];
for (int i = 0; i < userInput.length; i++)
userInput[i] = sc.nextInt();
System.out.println(
"do you want it ascending or descending order. If you want it in ascending press 1 or if you want descending press 2");
order = sc.nextInt();
System.out.print("expenses not sorted : ");
printExpenses(userInput);
if (order == 1) {
expensesAscending(userInput);
} else if (order == 2) {
expensedescending(userInput);
}
}
public static void printExpenses(int[] arr) {
// this is were it is printed
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i] + "$");
}
}
public static void expensedescending(int arr[]) {
// This is were the selection sort starts
int N = arr.length;
for (int i = 0; i < N; i++) {
int small = arr[i];
int pos = i;
for (int j = i + 1; j < N; j++) {
if (arr[j] > small) {
small = arr[j];
pos = j;
}
}
int temp = arr[pos];
arr[pos] = arr[i];
arr[i] = temp;
System.out.println(": ");
// Printing array after pass
printExpenses(arr);
}
}
public static void expensesAscending(int arr[]) {
int N = arr.length;
for (int i = 1; i < N; i++) {
int j = i - 1;
int temp = arr[i];
while (j >= 0 && temp < arr[j]) {
arr[j + 1] = arr[j];
j--;
;
}
arr[j + 1] = temp;
System.out.println(": ");
// Printing array after pass
printExpenses(arr);
}
}
}