I have created method for quick sort algorithm using generics, I am trying to implement this method but I am trying to implement the so it will quick sort any variables with in the array such as numbers, string, char and so on. i have implemented this class.
this is my AssertRayTool class.
package arraySorter;
import RandomArray.RandomArray;
public abstract class ArraySortTool<T extends Comparable<T>> implements ArraySort<T>
{
private double timeTakenMillis(T[] array) {
double startTime = System.nanoTime();
sort(array);
return ((System.nanoTime()-startTime)/1000000.0);
}
public void timeInMillis(RandomArray<T> generator,int noPerSize,int maxTimeSeconds)
{
int size = 1; // initial size of array to test
int step = 1; // initial size increase
int stepFactor = 10; // when size reaches 10*current size increase step size by 10
double averageTimeTaken;
do {
double totalTimeTaken = 0;
for (int count = 0; count < noPerSize; count++) {
T[] array = generator.randomArray(size);
totalTimeTaken += timeTakenMillis(array);
}
averageTimeTaken = totalTimeTaken/noPerSize;
System.out.format("Average time to sort %d elements was %.3f milliseconds.\n",size,averageTimeTaken);
size += step;
if (size >= stepFactor*step) step *= stepFactor;
} while (averageTimeTaken < maxTimeSeconds*1000);
System.out.println("Tests ended.");
}
public boolean isSorted(T[] array) {
int detectedDirection = 0; // have not yet detected increasing or decreasing
T previous = array[0];
for (int index = 1; index < array.length; index++) {
int currentDirection = previous.compareTo(array[index]); // compare previous and current entry
if (currentDirection != 0) { // if current pair increasing or decreasing
if (detectedDirection == 0) { // if previously no direction detected
detectedDirection = currentDirection; // remember current direction
} else if (detectedDirection * currentDirection < 0) { // otherwise compare current and previous direction
return false; // if they differ array is not sorted
}
}
previous = array[index];
}
// reached end of array without detecting pairs out of order
return true;
}
public void sort(T[] array) {
// TODO Auto-generated method stub
}
}
this is my Quicksort class which extends the above class.
package arraySorter;
public class QuickSort<T extends Comparable<T>> extends ArraySortTool<T>
{
private T array[];
private int length;
public void sort(T[] array) {
if (array == null || array.length == 0) {
return;
}
this.array = array;
length = array.length;
quickSort(0, length - 1);
}
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
int pivot = [lowerIndex+(higherIndex-lowerIndex)/2];
// Divide into two arrays
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
exchangeValues(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
}
private void exchangevalues(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
From what I can see you're treating your generic array only as an array of integers. To fix that
int pivot = [lowerIndex+(higherIndex-lowerIndex)/2];
Becomes
T pivot = [lowerIndex+(higherIndex-lowerIndex)/2];
And
while (array[i] < pivot)
i++;
while (array[j] > pivot) {
j--;
Becomes
while (array[i].compareTo(pivot) < 0)
i++;
while (array[j].compareTo(pivot) > 0)
j--;
Also, don't forget that your T class must implement Comparable, otherwise you won't be able to compare objects.
Related
I have some problems with java.lang.ArrayIndexOutOfBoundsException: 10,
if i set 1 instead of 0 - i will have sorted array with unsorted first element, if i set 0 - i have error
public void quicksort() {
// Recursion
quicksort(0, counter - 1);
}
Here is all my code
public class Main {
private static int comparations = 0;
private static int swaps = 0;
int[] array;
int[] a;
int counter = 0;
int size;
public void qwe() throws IOException {
Scanner scan = new Scanner(new File("input.txt")); //provide file name from outside
while(scan.hasNextInt())
{
counter++;
scan.nextInt();
}
System.out.println(counter);
Scanner scan2 = new Scanner(new File("input.txt"));
a = new int[counter];
for(int i=0;i<counter;i++)
{
a[i]=scan2.nextInt(); //fill the array with the integers
}
}
public int partition(int p, int q) {
int i = p;
int j = q + 1;
// Get the pivot element from the middle of the list
int pivot = a[p];
// Divide into two lists
do {
// If the current value from the left list is smaller then the pivot
// element then get the next element from the left list
do {
i++;// As we not get we can increase i
} while (a[i] < pivot);
// If the current value from the right list is larger then the pivot
// element then get the next element from the right list
do {
j--;// As we not get we can increase j
} while (a[j] > pivot);
// If we have found a values in the left list which is larger then
// the pivot element and if we have found a value in the right list
// which is smaller then the pivot element then we exchange the
// values.
if (i < j) {
swap(i, j);
}
} while (i < j);
// swap the pivot element and j th element
swap(p, j);
return j;
}
private void swap(int p, int j) {
// exchange the elements
int temp = a[p];
a[p] = a[j];
a[j] = temp;
swaps++;
}
public void quicksort() {
// Recursion
quicksort(0, counter - 1);
}
public void quicksort(int p, int q) {
int j;
if (p < q) {
// Divide into two lists
j = partition(p, q);
// Recursion
quicksort(p, j - 1);
quicksort(j + 1, q);
}
comparations++;
}
public void print() {
// print the elements of array
for (int i = 0; i < counter; i++) {
System.out.print(a[i] + ",");
}
System.out.println();
}
public static void main(String args[]) throws IOException {
Main q = new Main();
q.qwe();
System.out.println("Before Sort <<<<<<<<<<<<<<<<<<<<<");
q.print();
q.quicksort();
System.out.println("After Sort > > > > > > > > > > > >");
q.print();
System.out.println("Comparisons: " + comparations);
System.out.println("Swaps: " + swaps);
}
}
use the condition in partition method
while(a[i] < pivot && i<q)
instead of
while(a[i] < pivot)
because you have to stop searching bigger value than pivot when you reach at the the end
I think you have to avoid do{...} while and use while instead.
Something like:
public int partition(int p, int q) {
int i = p;
int j = q + 1;
// Get the pivot element from the middle of the list
int pivot = a[p];
// Divide into two lists
while (i < j) {
// If the current value from the left list is smaller then the pivot
// element then get the next element from the left list
while (a[i] < pivot) {
i++;// As we not get we can increase i
}
// If the current value from the right list is larger then the pivot
// element then get the next element from the right list
while (a[j] > pivot) {
j--;// As we not get we can increase j
}
// If we have found a values in the left list which is larger then
// the pivot element and if we have found a value in the right list
// which is smaller then the pivot element then we exchange the
// values.
if (i < j) {
swap(i, j);
}
}
// swap the pivot element and j th element
swap(p, j);
return j;
}
I suspect your partition code isn't correct. As swap should be done on basis of value not on index.
if (i < j) {
swap(i, j);
}
Partitioning: reorder the array so that all elements with values
less than the pivot come before the pivot, while all elements with
values greater than the pivot come after it (equal values can go
either way). After this partitioning, the pivot is in its final
position. This is called the partition operation.
Also, why are you reading same file twice can't you get the number of elements and elements in same loop ?
As the title says I want to make a search algorithm that combines linearSearch and binarySearch. If the array has less than 20 elements I want to use linearSearch and otherwise binary Search.
-the array should be sorted.
-the array is of element of the type Comparable.
-The algorithm should return the index where the elements is found otherwise it should return -1
my code, but im a bit stuck.. am I on the right track?
public class SearchAlgorithm<T extends Comparable<T>> {
public int linearSearch(T[] Array, T find){
int temp = 0;
for(int i = 0; i < Array.length; i++){
if(Array[i] == find){
temp = i;
}
else{
temp = -1;
}
}
return temp;
}
public int binarySearch(T[] Array, T find){
int lowIdx = 0;
int highIdx = Array.length-1;
int middleIdx = 0;
while(lowIdx <= highIdx){
middleIdx = (highIdx + lowIdx)/2;
int comp = find.compareTo(Array[middleIdx]);
if(comp < 0)
lowIdx = middleIdx + 1;
else if(comp > 0)
highIdx = middleIdx -1;
else{
lowIdx = highIdx+1;
return middleIdx;
}
}
return -1;
}
public void combinedSearch(T[] Arr, T find){
long startTime = System.currentTimeMillis();
if(Arr.length < 20){
linearSearch(Arr,find);
}
else{
binarySearch(Arr,find);
}
long endTime = System.currentTimeMillis();
System.out.println("combinedSearch took: "+(endTime-startTime)+ "ms");
}
public static void main(String[] args){
int[] a = {1,2,3,4,5};
binarySearch(a,4);
}
}
For your linear search
if(Array[i] == find){
temp = i;
}
else{
temp = -1;
}
You set it -1 every time it doesn't match. It should be something like :
int temp = -1;
for(int i = 0; i < Array.length; i++){
if(Array[i] == find){
temp = i;
return temp;
}
}
return temp;
Also for your binary search, you should reverse the comparison. Number you are finding is in left half if its less than mid and so on.
if(comp > 0)
lowIdx = middleIdx + 1;
else if(comp < 0)
highIdx = middleIdx -1;
I'm trying to create and sort a heap using this array in Java. I keep getting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 42
at HeapSort.exchange(HeapSort.java:28)
at HeapSort.Max_Heapify(HeapSort.java:22)
at HeapSort.Build_Heap at HeapSort.Sort(HeapSort.java:36)
at HeapSort.main(HeapSort.java:46)
I'm not sure where the error is coming from.
public class HeapSort {
public static int n;
public static int[] a;
public static int largest;
public static void Build_Heap(int[] a){
n = a.length-1;
for(int i = n/2; i >= 0; i--){
Max_Heapify(a,i);
}
}
public static void Max_Heapify(int[] a,int i){
int left = 2*i;
int right = 2*i +1;
if(left <= n && a[left] > a[i])
largest = left;
if(right <=n && a[right] > a[largest])
largest = right;
if(largest != i)
exchange (a[i],a[largest]);
Max_Heapify(a,largest);
}
private static void exchange(int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
// TODO Auto-generated method stub
}
public static void Sort(int[] a0){
a = a0;
Build_Heap(a);
for(int i = n; i > 0; i--){
exchange(0,i);
n = n-1;
Max_Heapify(a,0);
}
}
public static void main(String[] args){
int[] a1 = {3,55,6,42,34,56,34};
Sort(a1);
for(int i = 0; i < a1.length; i++){
System.out.print(a1[i] + " ");
}
}
}
You are getting an error in exchange(). The parameters i and j for that method look like to be indexes of the array a. But, you are calling the method exchange(a[i],a[largest]) which is passing the value of from the array at indexes i and largest instead of passing the actual indexes i and largest to the method.
Try calling exchange like exchange(i,largest)
The exchange call (on line 22) in Max_Heapify() is given the values of the array at those locations instead of the locations (the indexes, i and largest) that can be anything, in this example, 42 which is larger than the array to be sorted length,
I wrote a program for this problem:
“Write a program that, given an array array[] of n numbers and another number x, determines whether or not there exist two elements in array whose sum is exactly x.”
Which is this:
boolean hasArrayTwoCandidates (int array[], int sum) {
int length = array.length;
quickSort(array, 0, length-1);
int first, last;
first = 0;
last = length-1;
while(first < last){
if( array[first] + array[last] == sum )
return true;
else if( array[first] + array[last] < sum )
first++;
else // array[i] + array[j] > sum
last--;
}
return false;
}
At first place, I don't know where should I put or add "quick sort" codes. I have this problem with other programs, as well; when I want to add written methods to the present one.
Should I create a "new class" under this "project" and put "quicksort" codes there?
Should I put them in this class? but how can I use it?
At second place, I don't know what should I write in my "main method"?
this is my quicksort codes:
public void sort(int[] values) {
if (values == null || values.length == 0){
return;
}
this.array = values;
length = values.length;
quickSort(this.array, 0, length - 1);
}
private void quickSort(int[] array, int low, int high) {
int i = low, j = high;
int pivot = array[low + (high-low)/2];
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
if (low < j)
quickSort(array, low, j);
if (i < high)
quickSort(array, i, high);
}
private void exchange(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
actually, I dont know what should I write in my "main method" to run this program?
For you Question you can do simply this kind of coding in main method:
public static void main(String[]args) {
int x = 20;
int[] arr = {2,5,4,10,12,5};
System.out.println(hasArrayTwoCandidates(arr,x));
}
make the methods static
static boolean hasArrayTwoCandidates (int array[], int sum)
But there are porblems in your coding:
private void exchange(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Here the array is not defined. you'll get an error. you have to pass the array too to the method make it as.
private void exchange(int i, int j,int[] array)
But since you are not necessary to do sorting. I recommend this.
static boolean hasArrayTwoCandidates (int array[], int sum) {
boolean flag = false;
for(int i=0;i<array.length-1;i++){
for(int j=i+1;j<array.length ;j++){
if(array[i]+array[j] == sum)
flag = true;
}
}
return flag;
}
this will get one element and check while adding other elements that it is true
Then the main method come same way.
you can put all those method in same class, make hasArrayTwoCandidates() static (Note that main method is static and a static method can have access only to static methods)
public static boolean hasArrayTwoCandidates (int array[], int sum) {
....
}
and in your main method you can test it like this :
public static void main(String[] args){
int[] arr = {2,5,12,5,2,7,15};
System.out.print(hasArrayTwoCandidates(arr, 27));
}
Answering your questions: you can write methods and call them within the same class, just write them with the static modifier:
private static <return_type> <methodName> (<type> param1, <type> param2) {
// Your code here
}
For a program like this, I don't get why you are thinking about sorting the array before checking the sum of 2 numbers within it, when you could do all at once. Check out this code, this may shine a light on you. It is straight-forward and only to see if it clarifies your logic.
import java.util.Random;
public class VerifySum {
public static void main(String[] args) {
Random rand = new Random();
int[] array = new int[10];
// Produce a random number from 10 to 20
int randomSum = rand.nextInt(11) + 10;
// Fill out the array with random integers from 0 to 10
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(11);
}
// Check all array indexes against each other
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] + array[j] == randomSum) {
System.out.println(array[i] + " + " + array[j] + " = " + randomSum);
}
}
}
// Print "x"
System.out.println("randomSum = " + randomSum);
// Print array for verification of the functionality
for (int i = 0; i < array.length; i++) {
System.out.println("array [" + i + "] = " + array[i]);
}
}
}
Sometimes making it simpler is more efficient. ;-)
I'm having a bit of a problem writing a recursive function that sorts an array in java recursively . Right now it appears as though I have an infinite loop, and I can't seem to figure out where.
The primary function "rec_piv" searches from index1 to the pivot point and sorts the first half, then switches from the pivot point to the length of the array and sorts the second half. All of the comparisons are recorded by an int. [The array is of random size from 2 to 2014]
Thanks very much in advance!
public class Recursive_pivot {
private Random random_size = new Random();
private int size = random_size.nextInt(1024) + 2;
public int[] a = new int[size];
private Random elements = new Random();
/* variable for rec_piv */
public int temp=0;
public int temp2=0;
private Random rand_pivot = new Random();
private int pivot = rand_pivot.nextInt(size) + 2;
private int first_half =a[0+1];
private int second_half=a[pivot+1];
private int first_index=0; //first half of the array
private int second_index=pivot; //second half of the array
//The pivot is randomly chosen.
public int comparisons =0; //count the number of comparisons.
public void fill(){
for (int q=0; q<a.length; q++) {
/* filling the array */
a[q] = elements.nextInt(100 ) + 1;
}
}
public void rec_piv(int first_index, int second_index) {
if(first_index < pivot) {
if(first_half > a[first_index]) {
comparisons++;
temp = a[first_index];
a[first_index] = a[first_half];
a[first_half] = temp;
}
rec_piv(first_index+1, second_index);
}
if(second_index < a.length) {
if(second_half > a[second_index]) {
comparisons++;
temp2 = a[second_index];
a[second_index] = a[second_half];
a[second_half] = temp2;
}
rec_piv(first_index, second_index+1);
}
} //end of rec_piv
}//end of class.
You are trying to do a QSort here is a simple version of it.
public void quickSort(int array[], int start, int end)
{
int i = start; // index of left-to-right scan
int k = end; // index of right-to-left scan
if (end - start >= 1) // check that there are at least two elements to sort
{
int pivot = array[start];
while (k > i)
{
while (array[i] <= pivot && i <= end && k > i)
i++;
while (array[k] > pivot && k >= start && k >= i)
k--;
if (k > i)
swap(array, i, k);
}
swap(array, start, k);
quickSort(array, start, k - 1); // quicksort the left partition
quickSort(array, k + 1, end); // quicksort the right partition
}
else // if there is only one element in the partition, do not do any sorting
{
return; // the array is sorted, so exit
}
}
public void swap(int array[], int index1, int index2)
// pre: array is full and index1, index2 < array.length
// post: the values at indices 1 and 2 have been swapped
{
int temp = array[index1]; // store the first value in a temp
array[index1] = array[index2]; // copy the value of the second into the first
array[index2] = temp; // copy the value of the temp into the second
}
from this site.
http://www.mycstutorials.com/articles/sorting/quicksort