Using Binary Search with sorted Array with duplicates [duplicate] - java
This question already has answers here:
Finding multiple entries with binary search
(15 answers)
Closed 3 years ago.
I've been tasked with creating a method that will print all the indices where value x is found in a sorted array.
I understand that if we just scanned through the array from 0 to N (length of array) it would have a running time of O(n) worst case. Since the array that will be passed into the method will be sorted, I'm assuming that I can take advantage of using a Binary Search since this will be O(log n). However, this only works if the array has unique values. Since the Binary Search will finish after the first "find" of a particular value. I was thinking of doing a Binary Search for finding x in the sorted array, and then checking all values before and after this index, but then if the array contained all x values, it doesn't seem like it would be that much better.
I guess what I'm asking is, is there a better way to find all the indices for a particular value in a sorted array that is better than O(n)?
public void PrintIndicesForValue42(int[] sortedArrayOfInts)
{
// search through the sortedArrayOfInts
// print all indices where we find the number 42.
}
Ex: sortedArray = { 1, 13, 42, 42, 42, 77, 78 } would print: "42 was found at Indices: 2, 3, 4"
You will get the result in O(lg n)
public static void PrintIndicesForValue(int[] numbers, int target) {
if (numbers == null)
return;
int low = 0, high = numbers.length - 1;
// get the start index of target number
int startIndex = -1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (numbers[mid] > target) {
high = mid - 1;
} else if (numbers[mid] == target) {
startIndex = mid;
high = mid - 1;
} else
low = mid + 1;
}
// get the end index of target number
int endIndex = -1;
low = 0;
high = numbers.length - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (numbers[mid] > target) {
high = mid - 1;
} else if (numbers[mid] == target) {
endIndex = mid;
low = mid + 1;
} else
low = mid + 1;
}
if (startIndex != -1 && endIndex != -1){
for(int i=0; i+startIndex<=endIndex;i++){
if(i>0)
System.out.print(',');
System.out.print(i+startIndex);
}
}
}
Well, if you actually do have a sorted array, you can do a binary search until you find one of the indexes you're looking for, and from there, the rest should be easy to find since they're all next to each-other.
once you've found your first one, than you go find all the instances before it, and then all the instances after it.
Using that method you should get roughly O(lg(n)+k) where k is the number of occurrences of the value that you're searching for.
EDIT:
And, No, you will never be able to access all k values in anything less than O(k) time.
Second edit: so that I can feel as though I'm actually contributing something useful:
Instead of just searching for the first and last occurrences of X than you can do a binary search for the first occurence and a binary search for the last occurrence. which will result in O(lg(n)) total. once you've done that, you'll know that all the between indexes also contain X(assuming that it's sorted)
You can do this by searching checking if the value is equal to x , AND checking if the value to the left(or right depending on whether you're looking for the first occurrence or the last occurrence) is equal to x.
public void PrintIndicesForValue42(int[] sortedArrayOfInts) {
int index_occurrence_of_42 = left = right = binarySearch(sortedArrayOfInts, 42);
while (left - 1 >= 0) {
if (sortedArrayOfInts[left-1] == 42)
left--;
}
while (right + 1 < sortedArrayOfInts.length) {
if (sortedArrayOfInts[right+1] == 42)
right++;
}
System.out.println("Indices are from: " + left + " to " + right);
}
This would run in O(log(n) + #occurrences)
Read and understand the code. It's simple enough.
Below is the java code which returns the range for which the search-key is spread in the given sorted array:
public static int doBinarySearchRec(int[] array, int start, int end, int n) {
if (start > end) {
return -1;
}
int mid = start + (end - start) / 2;
if (n == array[mid]) {
return mid;
} else if (n < array[mid]) {
return doBinarySearchRec(array, start, mid - 1, n);
} else {
return doBinarySearchRec(array, mid + 1, end, n);
}
}
/**
* Given a sorted array with duplicates and a number, find the range in the
* form of (startIndex, endIndex) of that number. For example,
*
* find_range({0 2 3 3 3 10 10}, 3) should return (2,4). find_range({0 2 3 3
* 3 10 10}, 6) should return (-1,-1). The array and the number of
* duplicates can be large.
*
*/
public static int[] binarySearchArrayWithDup(int[] array, int n) {
if (null == array) {
return null;
}
int firstMatch = doBinarySearchRec(array, 0, array.length - 1, n);
int[] resultArray = { -1, -1 };
if (firstMatch == -1) {
return resultArray;
}
int leftMost = firstMatch;
int rightMost = firstMatch;
for (int result = doBinarySearchRec(array, 0, leftMost - 1, n); result != -1;) {
leftMost = result;
result = doBinarySearchRec(array, 0, leftMost - 1, n);
}
for (int result = doBinarySearchRec(array, rightMost + 1, array.length - 1, n); result != -1;) {
rightMost = result;
result = doBinarySearchRec(array, rightMost + 1, array.length - 1, n);
}
resultArray[0] = leftMost;
resultArray[1] = rightMost;
return resultArray;
}
Another result for log(n) binary search for leftmost target and rightmost target. This is in C++, but I think it is quite readable.
The idea is that we always end up when left = right + 1. So, to find leftmost target, if we can move right to rightmost number which is less than target, left will be at the leftmost target.
For leftmost target:
int binary_search(vector<int>& nums, int target){
int n = nums.size();
int left = 0, right = n - 1;
// carry right to the greatest number which is less than target.
while(left <= right){
int mid = (left + right) / 2;
if(nums[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
// when we are here, right is at the index of greatest number
// which is less than target and since left is at the next,
// it is at the first target's index
return left;
}
For the rightmost target, the idea is very similar:
int binary_search(vector<int>& nums, int target){
while(left <= right){
int mid = (left + right) / 2;
// carry left to the smallest number which is greater than target.
if(nums[mid] <= target)
left = mid + 1;
else
right = mid - 1;
}
// when we are here, left is at the index of smallest number
// which is greater than target and since right is at the next,
// it is at the first target's index
return right;
}
I came up with the solution using binary search, only thing is to do the binary search on both the sides if the match is found.
public static void main(String[] args) {
int a[] ={1,2,2,5,5,6,8,9,10};
System.out.println(2+" IS AVAILABLE AT = "+findDuplicateOfN(a, 0, a.length-1, 2));
System.out.println(5+" IS AVAILABLE AT = "+findDuplicateOfN(a, 0, a.length-1, 5));
int a1[] ={2,2,2,2,2,2,2,2,2};
System.out.println(2+" IS AVAILABLE AT = "+findDuplicateOfN(a1, 0, a1.length-1, 2));
int a2[] ={1,2,3,4,5,6,7,8,9};
System.out.println(10+" IS AVAILABLE AT = "+findDuplicateOfN(a2, 0, a2.length-1, 10));
}
public static String findDuplicateOfN(int[] a, int l, int h, int x){
if(l>h){
return "";
}
int m = (h-l)/2+l;
if(a[m] == x){
String matchedIndexs = ""+m;
matchedIndexs = matchedIndexs+findDuplicateOfN(a, l, m-1, x);
matchedIndexs = matchedIndexs+findDuplicateOfN(a, m+1, h, x);
return matchedIndexs;
}else if(a[m]>x){
return findDuplicateOfN(a, l, m-1, x);
}else{
return findDuplicateOfN(a, m+1, h, x);
}
}
2 IS AVAILABLE AT = 12
5 IS AVAILABLE AT = 43
2 IS AVAILABLE AT = 410236578
10 IS AVAILABLE AT =
I think this is still providing the results in O(logn) complexity.
A Hashmap might work, if you're not required to use a binary search.
Create a HashMap where the Key is the value itself, and then value is an array of indices where that value is in the array. Loop through your array, updating each array in the HashMap for each value.
Lookup time for the indices for each value will be ~ O(1), and creating the map itself will be ~ O(n).
Find_Key(int arr[], int size, int key){
int begin = 0;
int end = size - 1;
int mid = end / 2;
int res = INT_MIN;
while (begin != mid)
{
if (arr[mid] < key)
begin = mid;
else
{
end = mid;
if(arr[mid] == key)
res = mid;
}
mid = (end + begin )/2;
}
return res;
}
Assuming the array of ints is in ascending sorted order; Returns the index of the first index of key occurrence or INT_MIN. Runs in O(lg n).
It is using Modified Binary Search. It will be O(LogN). Space complexity will be O(1).
We are calling BinarySearchModified two times. One for finding start index of element and another for finding end index of element.
private static int BinarySearchModified(int[] input, double toSearch)
{
int start = 0;
int end = input.Length - 1;
while (start <= end)
{
int mid = start + (end - start)/2;
if (toSearch < input[mid]) end = mid - 1;
else start = mid + 1;
}
return start;
}
public static Result GetRange(int[] input, int toSearch)
{
if (input == null) return new Result(-1, -1);
int low = BinarySearchModified(input, toSearch - 0.5);
if ((low >= input.Length) || (input[low] != toSearch)) return new Result(-1, -1);
int high = BinarySearchModified(input, toSearch + 0.5);
return new Result(low, high - 1);
}
public struct Result
{
public int LowIndex;
public int HighIndex;
public Result(int low, int high)
{
LowIndex = low;
HighIndex = high;
}
}
public void printCopies(int[] array)
{
HashMap<Integer, Integer> memberMap = new HashMap<Integer, Integer>();
for(int i = 0; i < array.size; i++)
if(!memberMap.contains(array[i]))
memberMap.put(array[i], 1);
else
{
int temp = memberMap.get(array[i]); //get the number of occurances
memberMap.put(array[i], ++temp); //increment his occurance
}
//check keys which occured more than once
//dump them in a ArrayList
//return this ArrayList
}
Alternatevely, instead of counting the number of occurances, you can put their indices in a arraylist and put that in the map instead of the count.
HashMap<Integer, ArrayList<Integer>>
//the integer is the value, the arraylist a list of their indices
public void printCopies(int[] array)
{
HashMap<Integer, ArrayList<Integer>> memberMap = new HashMap<Integer, ArrayList<Integer>>();
for(int i = 0; i < array.size; i++)
if(!memberMap.contains(array[i]))
{
ArrayList temp = new ArrayList();
temp.add(i);
memberMap.put(array[i], temp);
}
else
{
ArrayList temp = memberMap.get(array[i]); //get the lsit of indices
temp.add(i);
memberMap.put(array[i], temp); //update the index list
}
//check keys which return lists with length > 1
//handle the result any way you want
}
heh, i guess this will have to be posted.
int predefinedDuplicate = //value here;
int index = Arrays.binarySearch(array, predefinedDuplicate);
int leftIndex, rightIndex;
//search left
for(leftIndex = index; array[leftIndex] == array[index]; leftIndex--); //let it run thru it
//leftIndex is now the first different element to the left of this duplicate number string
for(rightIndex = index; array[rightIndex] == array[index]; rightIndex++); //let it run thru it
//right index contains the first different element to the right of the string
//you can arraycopy this [leftIndex+1, rightIndex-1] string or just print it
for(int i = leftIndex+1; i<rightIndex; i++)
System.out.println(array[i] + "\t");
Related
Sorted Search, count numbers less than target value
I am practicing a sorted search task, from testdome.com /** * Implement function countNumbers that accepts a sorted array of unique integers and, * efficiently with respect to time used, counts the number of array elements that are less than the parameter lessThan. * <p> * For example, SortedSearch.countNumbers(new int[] { 1, 3, 5, 7 }, 4) * should return 2 because there are two array elements less than 4. */ Currently according to the site my answer has a score of 50 % due to edge cases and performance, im trying to get an opinion on what i might need to add or a different approach. Here is my code public static int countNumbers(int[] sortedArray, int lessThan) { int count = 0; if(sortedArray == null) { return 0; } List<Integer> numbers = new ArrayList<>(); for (int i = 0; i < sortedArray.length; i++) { if (sortedArray[i] < lessThan) { count++; } else { break; } } return count; } And the result i get when i test it on their environment is as follows Example case: Correct answer Various small arrays: Correct answer Performance test when sortedArray contains lessThan: Time limit exceeded Performance test when sortedArray doesn't contain lessThan: Time limit exceeded so two performance tests fail even though i cant see this tests may be i could get a suggestion here
If O(n) is giving TLE. You need something faster than O(n). Binary Search is O(logN). public static int countNumbers(int[] sortedArray, int lessThan) { int start = 0; int end = sortedArray.length - 1; int mid = 0; while (start <= end) { mid = start + (end - start) / 2; if (sortedArray[mid] < lessThan) { if (mid < sortedArray.length - 1 && sortedArray[mid + 1] < lessThan) { start = mid + 1; continue; } else { return mid + 1; } } if (sortedArray[mid] >= lessThan) { end = mid - 1; } else { start = mid + 1; } } return 0; } Or use built-in Binary Search: Arrays.binarySearch(new int[]{1, 2, 4}, 3) + 1) * -1; When the key is not found, it returns negative insertion position. To convert it to index, I did + 1 and multiplied by - 1 to make it positive.
Search method that finds an element by cutting an array in halves (Java)
I'm working on an assignment. What I must create is a method that searches for an specific int in an array. It is assumed that the array is already sorted from lowest to highest number. But the condition is that it must search by cutting said array by half and checking in which of the halves the target number is in, then cut said half in half again and so on so on. We were asked not to use recursive methods as well. This is the code I came up with but I fail to see my mistake, any help to understand the problem better is more than appreciated!!! public static boolean SearchInHalf(int[] array, int targetint) { int fin = array[array.length-1]; int init = array[0]; int range = fin-init; if ( targetint>array[array.length-1] || targetint< array[0]) { return false; } while (range>=2) { int half = array[range/2]; if (targetint>half) { init = half; range = fin-init; half = array[range/2]; } else if (targetint<half) { fin = half; range = fin-init; half = array[range/2]; } else if (targetint==half || targetint==fin || targetint==init) { return true; } } return false; }
Your problem is known as the "Binary Search". For binary search to work, the elements in the array must already be ordered (which is your case, let's assume ascending). The binary search first compares the key with the element in the middle of the array: If the key is less than the middle element, you need to continue to search for the key only in the first half of the array. If the key is greater than the middle element, you need to continue to search for the key only in the second half of the array. If the key is equal to the middle element, the search ends with a match. So binary search method eliminates at least half of the array after each comparison. Assuming you will call this method in your static main function: public static int binarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; while(high >= low) { //search array until there is a single element left int mid = (low + high) / 2; //mark middle index if (key < list[mid]) //if key is smaller than the middle element.. high = mid - 1; //new high is the middle element else if (key == list[mid]) //if key=middle element --> voila! return mid; //returns the index of searched element if it is in your array else low = mid + 1; //if key is greater than the middle element new low is middle element } return –low - 1; //high < low, key not found }
Solved it like this: while (true) { if (targetint>array[array.length-1] || targetint<array[0]) return false; int middleInt = array[Math.round(array.length/2)]; if (middleInt == targetint) { return true; } else if (targetint<middleInt) { int[] firstHalf = new int[array.length/2]; System.arraycopy(array, 0, firstHalf, 0, firstHalf.length); array = firstHalf; } else if (targetint>middleInt) { int[] secondHalf = new int[array.length/2]; System.arraycopy(array, array.length/2, secondHalf, 0, secondHalf.length); array = secondHalf; } else if(array.length == 1) return false; }
Using binary search to count number of elements smaller/larger than a given number
Given a number current, find the number of values in an array which are larger and smaller than that value. //sort array for binary search int[] digits = Arrays.stream(sc.nextLine() .split(" ")) .mapToInt(Integer::parseInt) .sorted() .toArray(); //for duplicate values, find higher index of current. while(low <= high){ int mid = low + (high - low)/2; if(digits[mid] > current){ high = mid - 1; }else if (digits[mid] == current){ startindex = mid; high = mid - 1; }else{ startindex = mid; low = mid +1; } } //for duplicate values, find lower index of current. int endindex = -1; low = 0; high = no_digits - 1; while(low <= high){ int mid = low + (high - low)/2; if(digits[mid] > current){ high = mid - 1; }else if (digits[mid] == current){ endindex = mid; low = mid + 1; }else{ endindex = mid; low = mid + 1; } } System.out.println(endindex + "-" + startindex); if(digits[0] > current){ smallest = 0; largest = no_digits; System.out.println(String.format("Smaller: %d, Greater: %d", smallest, largest)); } else if (digits[no_digits - 1] < current){ smallest = no_digits; largest = 0; System.out.println(String.format("Smaller: %d, Greater: %d", smallest, largest)); }else { smallest = startindex; largest = no_digits - endindex - 1; System.out.println(String.format("Smaller: %d, Greater: %d", smallest, largest)); } } } Sample input: 5 8 7 2 4 3 7 9 1 9 - Array of ints. 7 0 100 3 6 Output: Smaller: 5, Greater: 3 Smaller: 0, Greater: 10 Smaller: 10, Greater: 0 Smaller: 2, Greater: 7 Smaller: 5, Greater: 5 My results: 6-5 //start and end index. Smaller: 5, Greater: 3 -1--1 Smaller: 0, Greater: 10 9-9 Smaller: 10, Greater: 0 2-2 Smaller: 2, Greater: 7 4-4 Smaller: 5, Greater: 4 I managed to come out with the above algorithm which accounts for values larger or lower than any value in the array. However, I am unable to find a solution to account for values that are nonexistent in the array without iterating though the array since I need to accomplish the above in O((N+Q) log N) time. In this case, this would be the last test case where the value is 6. 6 does not exist in the array but I will still need to count all values higher/lower than 6.
Binary search algorithm produces the "insertion point" for values that do not exist in the array. Your startIndex and endIndex would give you the first "eligible" item, or the one right next to it. In other words, if you are looking for all values less than 6, the search for endpoint would yield the index of 5. Note that you don't need to roll your own binary search algorithm: Java provides an implementation for you. Reference: Arrays.binarySearch
EDIT The question has been edited, now it contains an additional requirement that the algorithm should work fast for multiple queries, more precisely: the overall runtime should be O((N + Q) * log(N)) where N is the size of the array and Q is the number of queries. The approach below works only for Q = 1. I don't see any reason not to do it in linear O(N) time. // get this from scanner int number = 5; int[] array = {6, 2, 7, 4, 1, 42}; // the "algorithm" int numLessThan = 0; int numGreaterThan = 0; for (int i: array) { if (i < number) numLessThan++; if (i > number) numGreaterThan++; } System.out.println( "Num greater than: " + numGreaterThan + " " + "Num less than: " + numLessThan ); Output: Num greater than: 3 Num less than: 3 If you insist on doing it with streams: long numLessThan = Arrays.stream(array).filter(x -> x < number).count(); long numGreaterThan = Arrays.stream(array).filter(x -> x > number).count(); Even though it traverses the array twice, it is still O(N).
Since you use a Stream anyway, with a map-call no less, you're iterating the whole array anyway. So just do class Counters { AtomicInteger smaller = new AtomicInteger(0); AtomicInteger larger = new AtomicInteger(0); private final int upperLimit; private final int lowerLimit; public Counters(int up, int down) { upperLimit = up; lowerLimit = down; } public void consider(int value) { if (value > upperLimit) larger.incrementAndGet(); if (value < lowerLimit) smaller.incrementAndGet(); } public int getSmaller() { return smaller.get(); } public int getLarger() { return larger.get(); } } Counters c = new Counters(upper, lower); IntStream.of(yourValues).parallel().forEach(c::consider); // your output here System.out.printf("Smaller: %d - Larger: %d", c.getSmaller(), c.getLarger()); or a more generic version class MatchCounter<T> { AtomicInteger count = new AtomicInteger(0); private final Predicate<T> match; public MatchCounter(Predicate<T> m) { match = m; } public void consider(T value) { if (m.test(value)) { count.incrementAndGet(); } } public int getCount() { return count.get(); } } MatchCounter<Integer> smaller = new MatchCounter<>(i -> i < lower); MatchCounter<Integer> larger = new MatchCounter<>(i -> i > upper); Consumer<Integer> exec = smaller::consider; Stream.of(yourArray).parallel().forEach(exec.andThen(larger::consider)); System.out.printf("Smaller: %d - Larger: %d", smaller.getCount(), larger.getCount());
See Arrays which would come handy here. void stats(int[] a, int sought) { a = Arrays.copyOf(a, a.length); Arrays.sort(a); int index = Arrays.binarySearch(a, sought); int smaller, larger; if (index < 0) { // Not found. index = ~index; // Insertion position. smaller = index; larger = index: } else { // Found. smaller = index; while (smaller > 0 && a[smaller] == sought) { --smaller; } while (index <= 0 && a[index] == sought) { ++index; } } larger = a.length - index; int equals = index - smaller; System.out.printf("Smaller %d, equal %d, larger %d.%n", smaller, equals, larger); } As you see, when finding an element, it would suffice to loop back O(N) which is less than sorting O(N log N). Faster - O(log N) instead of O(N) for that part - would be if one could do a binary search on sought - 0.5 and sought + 0.5. void stats(int[] a, int sought) { a = Arrays.copyOf(a, a.length); for (int i = 0; i < a.length; ++i) { a[i] *= 2; } Arrays.sort(a); int smallerI = Arrays.binarySearch(a, 2 * sought - 1); int largerI = Arrays.binarySearch(a, 2 * sought + 1); int smaller = ~smallerI; int larger = a.length - ~largerI; int equals = ~largerI - ~smallerI; System.out.printf("Smaller %d, equal %d, larger %d.%n", smaller, equals, larger); } This uses doubled integers, which has the drawback that the valid domain of array values is halved. In your case your own binary search algorithm should opt for this latter case (without doubling), using an implicit sought + 0.5, never finding, looking for an insertion position.
Okay, so after your edit you state you want to run several queries over the same array so preparation time is less important. To do that, build a red-black tree from the array; that will give you a sorted structure that allows a search in O(log N). So what you do for the "smaller" count is go to the left until you find a node with a value equal or larger than the lower limit; count all left children of that. Analogue for the larger (go to the right, find equal or smaller, count to the right). It won't matter if the item is not present in the array because you're looking for an "equal-or-larger" so if e.g. 6 is not present but you find a 5, you'll count from there - only you add 1 to the count.
You just have to filter and then count occurences. For example : public static void main(String[] args) { int[] values = {5, 8, 7, 2, 4, 3, 7, 9, 1, 9}; printCount(values, 7); printCount(values, 0); printCount(values, 100); printCount(values, 3); printCount(values, 6); } private static void printCount(int[] values, int value) { long smallerCount = Arrays.stream(values).filter(v -> v < value).count(); long largerCount = Arrays.stream(values).filter(v -> v > value).count(); System.out.println(String.format("Smaller : %d, Larger: %d", smallerCount, largerCount)); }
What counts as a binary search comparison?
I'm writing a program that determines how many comparisons it takes to run a binary search algorithm for a given number and sorted array. What I don't understand is what counts as a comparison. // returns the number of comparisons it takes to find key in sorted list, array public static int binarySearch(int key, int[] array) { int left = 0; int mid; int right = array.length - 1; int i = 0; while (true) { if (left > right) { mid = -1; break; } else { mid = (left + right)/2; if (key < array[mid]) { i++; right = mid - 1; } else if (key > array[mid]) { i++; left = mid + 1; } else { break; // success } } } return i; } The function returns i, which is supposed to be the total number of comparisons made in finding the key in array. But what defines a comparison? Is it any time there is a conditional? Thanks for any help, just trying to understand this concept.
Usually, a comparison occurs each time the key is compared to an array element. The code seems to not be counting that, though. It is counting how many times one of the search boundaries (left or right) is changed. It's not exactly the same thing being counted, but it's pretty close to the same thing, since the number of times a boundary is shifted is directly related to the number of times through the loop and hence to the number of times a comparison is made. At most, the two ways of counting will be off by 1 or 2 (I didn't bother to figure that out exactly). Note also that if one were to use the usual definition, the code could be rewritten to use Integer.compare(int,int) do a single comparison of key with array[mid] to determine whether key was less than, equal to, or greater than array[mid]. public static int binarySearch(int key, int[] array) { int left = 0; int mid; int right = array.length - 1; int i = 0; while (left <= right) { mid = (left + right)/2; int comp = Integer.compare(key, array[mid]); i++; if (comp < 0) { right = mid - 1; } else if (comp > 0) { left = mid + 1; } else { break; // success } } return i; }
Bubble Sort to gap sort modification
I've run in to a problem and need your guidance. Basically i managed to create this Bubble Sort method. How can i modify this to Gap Sort, that rather than comparing neighboring elements each time through the list, compares elements that are some number(i) positions apart, where (i) is an integer less than n. For example, the first element would be compared to the (i + 1) element, 2nd element to the (i + 2) element, nth element to the (n-i) element, etc. A single iteration is completed when all of the elements that can be compared, have been compared. On the next iteration, i is reduced by some number greater than 1 and the process continues until i is less than 1 public static void bubbleSort (Comparable[] data, int maxlength){ int position, scan; Comparable temp; for (position = maxlength; position >= 1; position--){ for (scan = 0; scan <= position – 1; scan++){ if (data[scan].compareTo(data[scan+1]) > 0){ // Swap the values temp = data[scan]; data[scan] = data[scan + 1]; data[scan + 1] = temp; } } } }
This code (found on http://www.daniweb.com/software-development/java/threads/238791/gap-sort) might help you: public static void gapSort (Comparable [] data, int size) { int index; int gap, top; Comparable temp; boolean exchanged; double SF = 1.3; gap = size; do { exchanged = false; gap = (int) (gap / SF); if (gap == 0){ gap = 1; } for (index = 1; index <= size - gap; index++) { if (data [index].compareTo(data [index + gap]) > 0) { temp = data [index]; data [index] = data [index + gap]; data [index + gap] = temp; exchanged = true; } } } while (exchanged || gap > 1); } Remember that the easiest way to sort an array of objects that implement the Comparable interface is usually Arrays.Sort()