import java.util.Scanner; public class sort { static void readIntoArrayOfInts(int [] a) { Scanner in= new Scanner(System.in); for (int i=0;i<a.length;i++) { System.out.print("> "); a[i]=in.nextInt(); } } static void printArrayOfInts(int [] a) { for (int i=0;i<a.length;i++) { System.out.print(a[i]+" "); } System.out.println(); } public static void SortArray(int[] a) { for (int i=0;i<a.length-1;i++) for (int j=i+1;j<a.length;j++) if (a[i]>a[j]) {int temp=a[i]; a[i]=a[j]; a[j]=temp;} } public static void main(String [] args) { int [] z = new int[5]; readIntoArrayOfInts(z); sort(z); //add this printArrayOfInts(z); } }
boolean rowAllSame(int i, String s) { boolean same=true; for (int j=0;j<N && same;j++) { same = s.compareTo(button[i][j].getText())==0; } return same; } boolean colAllSame(int i, String s) { boolean same=true; for (int j=0;j<N && same;j++) { same = s.compareTo(button[j][i].getText())==0; } return same; } boolean leftDiagAllSame(String s) { boolean same=true; for (int j=0;j<N && same;j++) { same = s.compareTo(button[j][j].getText())==0; } return same; } boolean rightDiagAllSame(String s) { boolean same=true; for (int j=0;j<N && same;j++) { same = s.compareTo(button[j][N-j-1].getText())==0; } return same; }
public static int linearSearchPos(int [ ] a, int thing) { int i; for (i=0;i<a.length;i++) { if (a[i]==thing) return i; } return -1; }
public static int binarySearchPos(int [ ] a, int thing) { int first=0,last=a.length-1; int mid; while (first <=last) { mid=first + (last-first)/2; if (thing==(a[mid])) return mid; else if (after(a[mid],thing)) last = mid-1; else first=mid+1; } return -1; } }
Exercise:
Write a program that puts 10000 random ints between 0 and 9999 into an array of ints (look up java.util.Random
in the API)
Your program should then read a number from the command line and print yes if the number is in the array and no otherwise. You should use both the linear and binary search above. You should also ammend the above methods so the program prints out how many times each loop is executed.
Study the following programs:
s.danicic@gold.ac.uk