(java)Why is bubblesort not sorting? - java

I'm planning on a sorting marathon where I'll look up pseudo-code for common sorting algorithms and try implement them in Java.
The first one I'm trying is bubblesort. I wrote the simplest form which appears to work fine:
package bubblesort;
public class Sort {
private static void swapElements(int[] array, int index1, int index2) {
int holder = array[index1];
array[index1] = array[index2];
array[index2] = holder;
}
public static void ascending(int[] array) {
boolean sorted = false;
while(!sorted) {
sorted = true; //if no elements are swapped, 'sorted' remains equal to true and the while-loop ends.
for(int i = 0; i < array.length - 1; i++) {
if(array[i] > array[i + 1]) {
swapElements(array, i, i + 1);
sorted = false;
}
}
}
}
}
However, since the highest value is brought to the last element each time the for-loop gets executed, I tried to improve it by leaving out elements at the end, introducing a new variable that counts how many times the whole array is checked:
package bubblesort;
public class Sort {
private static void swapElements(int[] array, int index1, int index2) {
int holder = array[index1];
array[index1] = array[index2];
array[index2] = holder;
}
public static void ascending(int[] array) {
int timesLooped = 0;
boolean sorted = false;
while(!sorted) {
sorted = true;
for(int i = 0; i < array.length - timesLooped - 1; i++) {
if(array[i] > array[i + 1]) {
swapElements(array, i, i + 1);
sorted = false;
}
timesLooped++;
}
}
}
}
This time the sort fails; only some of the elements in the array get sorted, others don't.
So my question is: What is wrong with the way I introduced the 'timesLooped' variable that attempts to avoid making unnecessary comparisons?

timesLopped++ shall be outside the for loop:
public static void ascending(int[] array) {
int timesLooped = 0;
boolean sorted = false;
while(!sorted) {
sorted = true;
for(int i = 0; i < array.length - timesLooped - 1; i++) {
if(array[i] > array[i + 1]) {
swapElements(array, i, i + 1);
sorted = false;
}
}
timesLooped++;
}
}

Related

Java- Sorting int array

I'm trying to use this method to sort an integer array in ascending order. But my for loop runs through it only once.
public void sortArray()
{
boolean sorted = false;
while(sorted == false)
{
int temp;
for(int i = 0; i < inArray.length - 1; i++)
{
if(inArray[i] > inArray[i + 1])
{
temp = inArray[i];
inArray[i] = inArray[i + 1];
anArray[i + 1] = temp;
}
}
sorted = true;
}
}
I know it has to do with how I'm handling that boolean flag, but I'm not sure how to go about fixing it. Any suggestions would be appreciated. Thanks in advance.
There are multiple issues here:
while (sorted = false) sets sorted to false and then tests the resulting value false, meaning that you never enter the loop body at all (not once as per your question).
If you fix that, your code will only run the while loop body once (thus leaving the array not sorted yet), because you have sorted = true as an unconditional statement at the end of the loop body.
You need to have a flag that assumes the array is sorted, and then is cleared if you find evidence it wasn't, something like:
public void sortArray()
{
boolean sorted;
do
{
sorted = true; // Assume it's sorted
int temp;
for(int i = 0; i < inArray.length - 1; i++)
{
if(inArray[i] > inArray[i + 1])
{
temp = inArray[i];
inArray[i] = inArray[i + 1];
anArray[i + 1] = temp;
sorted = false; // We changed something, so assume we need to do another pass
}
}
}
while (!sorted);
}
Side note: This is just a style thing, but it's generally best to scope variables as narrowly as possible. There's no need for temp to be outside the for loop or even outside the if block, move it inside the if block
public void sortArray()
{
boolean sorted;
do
{
sorted = true; // Assume it's sorted
for(int i = 0; i < inArray.length - 1; i++)
{
if(inArray[i] > inArray[i + 1])
{
int temp = inArray[i];
inArray[i] = inArray[i + 1];
anArray[i + 1] = temp;
sorted = false; // We changed something, so assume we need to do another pass
}
}
}
while (!sorted);
}
You currently are setting your sorted to true allways at the end of the loop. While of course it should only be true if actually no reshuffling took place.
One way to archieve this would be to set sorted to true at the start of your while loop, and set it to false when you detect that the array is not yet sorted and you do the switching of elements:
public void sortArray()
{
boolean sorted = false;
while(!sorted)
{
sorted = true;
int temp;
for(int i = 0; i < inArray.length - 1; i++)
{
if(inArray[i] > inArray[i + 1])
{
sorted = false; // array is not yet sorted
temp = inArray[i];
inArray[i] = inArray[i + 1];
anArray[i + 1] = temp;
}
}
}
}
My method which contains no java collections
public class Main {
public static void main(String[] args) {
/** By Boris Elkin 21.09.2018 в 22.59 MSK You can input any digits, sorting was made without collections on purpose.
**/
int[] a1=new int[]{1,245623,3,3,3,3454,6,8123,234,123123,797897};
int[] a2=new int[]{234234, 33,4234,5,646456,9,78};
int[] a3;
a3= collide(a1, a2);
a3=sort(a3);
checkArray(a3);
}
public static int[] collide(int[]a, int[]b){
int breakpoint=0;
int size=a.length+b.length;
int[]c=new int[size];
for(int i=0;i<a.length;i++){
c[i]=a[i];
breakpoint=i;
}
for(int i=breakpoint+1,j=0;j<b.length;i++, j++){
c[i]=b[j];
}
return c;
}
public static int[] sort(int a[]){
boolean engine=true;
while(engine) {
for(int i=0;i<a.length;i++){
int temp, temp2;
if ((i + 1 < a.length) && (a[i] > a[i + 1])) {
temp = a[i];
temp2 = a[i + 1];
a[i + 1] = temp;
a[i] = temp2;
}
}
if(checkThreadLogistic(a)){
engine=false;
}
}
return a;
}
private static boolean checkThreadLogistic(int[] a) {
return checkCertainElement(a);
}
private static boolean checkCertainElement(int[] a) {
for(int i=0;i<a.length;i++){
if(i>1){
for(int j=a.length;j>i;j--){
if(j<a.length) if(a[i]>a[j])return false;
}
}
}
return true;
}
public static void checkArray(int[]array){
for (int anArray : array) {
System.out.println(anArray + "");
}
}
}

bubbleSort() for an int Array Linked List in Java

I'm having trouble with a bubbleSort method for my very unique homework assignment.
We are supposed to use a sorting method of our choice to sort, get this, a linked list of int arrays. Not an ArrayList not just a LinkedList. It works like a linked list but the each Node contains an array of a capacity of 10 ints.
I am stuck on the sorting method. I chose bubbleSort just because it was used in the last assignment and I felt most familiar with it. Any tips for a better sorting method to try would be considered helpful as well.
Here is my code:
public void bubbleSort() {
current = head; // Start at the head ArrayNode
for (int i = 0; i < size; i++) { // iterate through each ArrayNode
currentArray = current.getArray(); // get the array in this ArrayNode
int in, out;
for (out = size-1; out > 1; out--) { // outer loop (backwards)
for (in = 0; in < out; in++) { // inner loop (forwards)
if (currentArray[in] > currentArray[in+1]) // out of order?
swap(in, in+1); // swap them!
}
}
current.setArray(currentArray);
current = current.getNext();
}
}// End bubbleSort() method
// A helper method for the bubble sort
private void swap(int one, int two) {
int temp = currentArray[one];
currentArray[one] = currentArray[two];
currentArray[two] = temp;
} // End swap() method
This is a picture example of what I am supposed to be doing.
I have found a solution with selectionsort. There are a few test values, just run it to see it.
I can provide further information if needed.
import java.util.ArrayList;
import java.util.Random;
public class ArrayedListSort {
int listsize = 5; // how many nodes
int maxValue = 99; // the highest value (0 to this)
int nodeSize = 3; // size for every node
public static void main(String[] args) {
// run non static
new ArrayedListSort().runTest();
}
/**
* Log function.
*/
public void log(Object s) {
System.out.println(s);
}
public void logNoBR(Object s) {
System.out.print(s);
}
/**
* Output of list we have.
*/
public void logMyList(ArrayList<ListNode> listNode, String name) {
log("=== LOG OUTPUT " + name + " ===");
for ( int i=0; i < listNode.size(); i++) {
logNoBR(" node <" + i + ">");
logNoBR(" (");
for (int j=0; j < listNode.get(i).getSize(); j++) {
if ( j != (listNode.get(i).getSize()-1)) // if not last add ","
logNoBR( listNode.get(i).getValueAt(j) + "," );
else
logNoBR( listNode.get(i).getValueAt(j) );
}
log(")");
}
log("=====================================\n");
}
public void runTest() {
// create example List
ArrayList<ListNode> myList = new ArrayList<ListNode>();
// fill the nodes with random values
for ( int i = 0; i < listsize; i++) {
myList.add(new ListNode(nodeSize));
for (int j=0; j < nodeSize; j++) {
int randomValue = new Random().nextInt(maxValue);
myList.get(i).addValue(randomValue);
}
}
logMyList(myList, "myList unsorted"); // to see what we have
// now lets sort it
myList = sortListNode(myList);
logMyList(myList, "myList sorted"); // what we have after sorting
}
/**
* Selectionsort
*/
public ArrayList<ListNode> sortListNode(ArrayList<ListNode> myList) {
ArrayList<ListNode> retList = new ArrayList<ListNode>();
for ( int i = 0; i < listsize; i++) {
retList.add(new ListNode(nodeSize));
}
int lastSmallest = myList.get(0).getValueAt(0);
while ( !myList.isEmpty() ) {
int lastJ=0, lastI=0;
for ( int i = 0; i < myList.size(); i++) {
for (int j=0; j < myList.get(i).getSize(); j++) {
if ( myList.get(i).getValueAt(j) <= lastSmallest ) {
lastSmallest = myList.get(i).getValueAt(j);
lastJ = j;
lastI = i;
//log("Found smallest element at <"+i+","+j+"> (" + lastSmallest + ")");
}
}
}
myList.get(lastI).removeValue(lastJ);
if ( myList.get(lastI).getSize() == 0 )
myList.remove(lastI);
// add value to new list
for ( int i = 0; i < listsize; i++) {
if ( retList.get(i).getSize() < retList.get(i).getMaxSize() ) {
retList.get(i).addValue(lastSmallest);
break;
}
}
lastSmallest = Integer.MAX_VALUE;
}
return retList;
}
public class ListNode {
private ArrayList<Integer> values = new ArrayList<Integer>();
private int maxSize;
public ListNode(int maxSize) {
this.maxSize = maxSize;
}
public ArrayList<Integer> getValues() {
return values;
}
public int getMaxSize() {
return maxSize;
}
public int getSize() {
return values.size();
}
public int getValueAt(int position) {
if ( position < values.size())
return values.get(position);
else
throw new IndexOutOfBoundsException();
}
public void addValue(int value) {
values.add(value);
}
public void removeValue(int position) {
if ( position < values.size()) {
values.remove(position);
} else
throw new IndexOutOfBoundsException();
}
}
}
Here we go. The trivial solution consist in extracting all the elements of each array node and store them in a single big array, sort that big array (using Bubble Sort, Quick Sort, Shell Sort, etc.) and finally reconstruct the linked list of arrays with the the sorted values. I am almost sure that is not exactly what are you looking for.
If you want to sort the numbers in place, I can think of the following algorithm:
As others have commented, you need a comparison function that determines if a node A goes before a node B. The following algorithm use the first idea but for each pair of nodes, e.g. A->[3, 9, 7] and B->[1, 6, 8] becomes [1, 3, 6, 7, 8, 9] and finally A->[1,3, 6] and B->[7, 8, 9]. If we apply this rearrangement for each possible pair will end up with a sorted linked list of arrays (I have no proof, though).
A = head;
while (A.hasNext()) {
arrayA = A.getArray();
B = A.getNext();
while (B.hasNext()) {
arrayB = B.getArray();
// concatenate two arrays
int[] C = new int[arrayA.size() + arrayB.size()];
int i;
for (i = 0; i < arrayA.size(); i++)
C[i] = arrayA[i];
for ( ; i < arrayA.size() + arrayB.size(); i++)
C[i] = arrayB[i-arrayA.size()];
// sort the new arrays using agains Bubble sort or any
// other method, or Arrays.sort()
Arrays.sort(C);
// now return the sorted values to the two arrays
for (i = 0; i < arrayA.size(); i++)
arrayA[i] = C[i];
for (i = 0; i < arrayB.size(); i++)
arrayB[i] = C[i+arrayA.size()];
}
}
This is kind of pseudo code because I haven't worked with linked lists in Java but I think you get the idea.
NOTE: I haven't tested the code, it may contain horrors.

Recursive binary search in an int array using only 1 parameter

How can i implement a recursive binary search in an int array using only 1 parameter in java ?
it tried but my code doesn't work. I implemented a class which its instances are objects having arrays and a count variable to detect how many elements are their in the array. any idea how can i implement the recursive binary search using only 1 parameter ?
public class LinearSortedArray {
int count;
int[] a;
public LinearSortedArray() {
count = 0;
}
public LinearSortedArray(int size) {
count = 0;
a = new int[size];
}
public static int[] copyingMethod(int startPoint, int endPoint,
LinearSortedArray arrayObj) {
int[] copyingArray = new int[endPoint - startPoint];
int j = startPoint;
for (int i = 0; i < copyingArray.length; i++) {
copyingArray[i] = arrayObj.a[j];
j++;
}
return copyingArray;
}
public int binarySearchRec(int x) {
if (count == 0) {
return -1;
}
int pivot = count / 2;
LinearSortedArray newArrayObj;
if (x > a[pivot]) {
newArrayObj = new LinearSortedArray(count - pivot);
newArrayObj.count = newArrayObj.a.length;
newArrayObj.a = copyingMethod(pivot, count, this);
for (int i = 0; i < newArrayObj.a.length; i++) {
System.out.print(newArrayObj.a[i]);
System.out.print(" ");
}
System.out.println();
return pivot + newArrayObj.binarySearchRec(x);
} else if (x < a[pivot]) {
newArrayObj = new LinearSortedArray(pivot);
newArrayObj.count = newArrayObj.a.length;
newArrayObj.a = copyingMethod(0, pivot, this);
for (int i = 0; i < newArrayObj.a.length; i++) {
System.out.print(newArrayObj.a[i]);
System.out.print(" ");
}
System.out.println();
return newArrayObj.binarySearchRec(x);
} else {
return pivot;
}
}
}
P.S.: The arrays are already sorted
Binary search really requires a range and a target value -- so if you're only passing one parameter, this has to be the target and this must encapsulate the array & range.
public class ArraySegment {
protected int[] array;
protected int boundLo;
protected int boundHi;
public class ArraySegment (int[] array) {
// entire array.
this( array, 0, array.length);
}
public class ArraySegment (int[] array, int lo, int hi) {
this.array = array;
this.boundLo = lo;
this.boundHi = hi;
}
public int binarySearch (int target) {
if (boundHi <= boundLo) {
return -1; // Empty; not found.
}
int pivot = (boundLo + boundHi) / 2;
int pivotEl = array[ pivot];
if (target == pivotEl) {
return pivot; // Found!
}
if (target < pivotEl) {
// recurse Left of pivot.
ArraySegment sub = new ArraySegment( array, boundLo, pivot);
return sub.binarySearch( target);
} else {
// recurse Right of pivot.
ArraySegment sub = new ArraySegment( array, pivot, boundHi);
return sub.binarySearch( target);
}
}
}
It's a little bit questionable what kind of result you should return -- there isn't a good answer with the question posed like this, as an "integer index" kinda defeats the purpose of the ArraySegment/ range wrapper, and returning an ArraySegment containing only the found value is also fairly useless.
PS: You really shouldn't be copying the array or it's contents, just passing round references to ranges on that array. Like java.lang.String is a range on a character array.
You could contrive a single-parameter by using the Value Object Pattern, where you pass one "wrapper" object, but the object has many fields.
For example:
class SearchParams {
int target;
int start;
int end;
SearchParams(t, s, e) {
target = t;
start = s;
end = e'
}
}
int search(SearchParams params) {
// some impl
return search(new SearchParams(params.target, a, b));
}
Technically, this is one parameter. Although it may not be in the spirit of the rules.

Implementing a binary insertion sort using binary search in Java

I'm having trouble combining these two algorithms together. I've been asked to modify Binary Search to return the index that an element should be inserted into an array. I've been then asked to implement a Binary Insertion Sort that uses my Binary Search to sort an array of randomly generated ints.
My Binary Search works the way it's supposed to, returning the correct index whenever I test it alone. I wrote out Binary Insertion Sort to get a feel for how it works, and got that to work as well. As soon as I combine the two together, it breaks. I know I'm implementing them incorrectly together, but I'm not sure where my problem lays.
Here's what I've got:
public class Assignment3
{
public static void main(String[] args)
{
int[] binary = { 1, 7, 4, 9, 10, 2, 6, 12, 3, 8, 5 };
ModifiedBinaryInsertionSort(binary);
}
static int ModifiedBinarySearch(int[] theArray, int theElement)
{
int leftIndex = 0;
int rightIndex = theArray.length - 1;
int middleIndex = 0;
while(leftIndex <= rightIndex)
{
middleIndex = (leftIndex + rightIndex) / 2;
if (theElement == theArray[middleIndex])
return middleIndex;
else if (theElement < theArray[middleIndex])
rightIndex = middleIndex - 1;
else
leftIndex = middleIndex + 1;
}
return middleIndex - 1;
}
static void ModifiedBinaryInsertionSort(int[] theArray)
{
int i = 0;
int[] returnArray = new int[theArray.length + 1];
for(i = 0; i < theArray.length; i++)
{
returnArray[ModifiedBinarySearch(theArray, theArray[i])] = theArray[i];
}
for(i = 0; i < theArray.length; i++)
{
System.out.print(returnArray[i] + " ");
}
}
}
The return value I get for this when I run it is 1 0 0 0 0 2 0 0 3 5 12. Any suggestions?
UPDATE: updated ModifiedBinaryInsertionSort
static void ModifiedBinaryInsertionSort(int[] theArray)
{
int index = 0;
int element = 0;
int[] returnArray = new int[theArray.length];
for (int i = 1; i < theArray.lenght - 1; i++)
{
element = theArray[i];
index = ModifiedBinarySearch(theArray, 0, i, element);
returnArray[i] = element;
while (index >= 0 && theArray[index] > element)
{
theArray[index + 1] = theArray[index];
index = index - 1;
}
returnArray[index + 1] = element;
}
}
Here is my method to sort an array of integers using binary search.
It modifies the array that is passed as argument.
public static void binaryInsertionSort(int[] a) {
if (a.length < 2)
return;
for (int i = 1; i < a.length; i++) {
int lowIndex = 0;
int highIndex = i;
int b = a[i];
//while loop for binary search
while(lowIndex < highIndex) {
int middle = lowIndex + (highIndex - lowIndex)/2; //avoid int overflow
if (b >= a[middle]) {
lowIndex = middle+1;
}
else {
highIndex = middle;
}
}
//replace elements of array
System.arraycopy(a, lowIndex, a, lowIndex+1, i-lowIndex);
a[lowIndex] = b;
}
}
How an insertion sort works is, it creates a new empty array B and, for each element in the unsorted array A, it binary searches into the section of B that has been built so far (From left to right), shifts all elements to the right of the location in B it choose one right and inserts the element in. So you are building up an at-all-times sorted array in B until it is the full size of B and contains everything in A.
Two things:
One, the binary search should be able to take an int startOfArray and an int endOfArray, and it will only binary search between those two points. This allows you to make it consider only the part of array B that is actually the sorted array.
Two, before inserting, you must move all elements one to the right before inserting into the gap you've made.
I realize this is old, but the answer to the question is that, perhaps a little unintuitively, "Middleindex - 1" will not be your insertion index in all cases.
If you run through a few cases on paper the problem should become apparent.
I have an extension method that solves this problem. To apply it to your situation, you would iterate through the existing list, inserting into an empty starting list.
public static void BinaryInsert<TItem, TKey>(this IList<TItem> list, TItem item, Func<TItem, TKey> sortfFunc)
where TKey : IComparable
{
if (list == null)
throw new ArgumentNullException("list");
int min = 0;
int max = list.Count - 1;
int index = 0;
TKey insertKey = sortfFunc(item);
while (min <= max)
{
index = (max + min) >> 1;
TItem value = list[index];
TKey compKey = sortfFunc(value);
int result = compKey.CompareTo(insertKey);
if (result == 0)
break;
if (result > 0)
max = index - 1;
else
min = index + 1;
}
if (index <= 0)
index = 0;
else if (index >= list.Count)
index = list.Count;
else
if (sortfFunc(list[index]).CompareTo(insertKey) < 0)
++index;
list.Insert(index, item);
}
Dude, I think you have some serious problem with your code. Unfortunately, you are missing the fruit (logic) of this algorithm. Your divine goal here is to get the index first, insertion is a cake walk, but index needs some sweat. Please don't see this algorithm unless you gave your best and desperate for it. Never give up, you already know the logic, your goal is to find it in you. Please let me know for any mistakes, discrepancies etc. Happy coding!!
public class Insertion {
private int[] a;
int n;
int c;
public Insertion()
{
a = new int[10];
n=0;
}
int find(int key)
{
int lowerbound = 0;
int upperbound = n-1;
while(true)
{
c = (lowerbound + upperbound)/2;
if(n==0)
return 0;
if(lowerbound>=upperbound)
{
if(a[c]<key)
return c++;
else
return c;
}
if(a[c]>key && a[c-1]<key)
return c;
else if (a[c]<key && a[c+1]>key)
return c++;
else
{
if(a[c]>key)
upperbound = c-1;
else
lowerbound = c+1;
}
}
}
void insert(int key)
{
find(key);
for(int k=n;k>c;k--)
{
a[k]=a[k-1];
}
a[c]=key;
n++;
}
void display()
{
for(int i=0;i<10;i++)
{
System.out.println(a[i]);
}
}
public static void main(String[] args)
{
Insertion i=new Insertion();
i.insert(56);
i.insert(1);
i.insert(78);
i.insert(3);
i.insert(4);
i.insert(200);
i.insert(6);
i.insert(7);
i.insert(1000);
i.insert(9);
i.display();
}
}

Array Out Of Bounds

The purpose of this program is to find the kth smallest element in an array without sorting the array using a recursive and nonrecursive decrease and conquer type method.
I was hoping someone could look over my code and try to help me with my array out of bounds error(s).
The method that is throwing these errors is the recursive selection the non recursive selection works fine.
My driver is also attached and everything should compile if you want to test my code.
public class KthSmallest
{
private int counter;
private int term;
private int[] A;
int SelectionNonRecursive(int A[], int kthSmallest, int sizeOfA)
{
this.A = A;
if(kthSmallest == 1 || kthSmallest == sizeOfA)
{
return (LinearSearch(kthSmallest, sizeOfA));
}
else
{
for(int i = 0; i<sizeOfA; i++)
{
counter = 0;
for(int j = 0; j<sizeOfA; j++)
{
if(A[i] < A[j])
{
counter++;
}
}
if((sizeOfA - counter) == kthSmallest)
{
return A[i];
}
}
}
return 0;
}
int SelectionRecursive(int A[], int kthSmallest, int sizeOfA)
{
this.A = A;
return Selection_R(0, sizeOfA - 1, kthSmallest);
}
int Selection_R(int l, int r, int kthSmallest)
{
if(l<r)
{
if(kthSmallest == 1 || kthSmallest == A.length)
{
return (LinearSearch(kthSmallest, A.length));
}
else
{
int s = LomutoPartition(l, r);
if(s == kthSmallest - 1)
{
return A[s];
}
else if(s > (A[0] + kthSmallest - 1))
{
Selection_R(l, s-1, kthSmallest);
}
else
{
Selection_R(s+1, r, kthSmallest);
}
}
}
return 0;
}
int LomutoPartition(int l, int r)
{
int pivot = A[l];
int s = l;
for(int i = l+1; i<r; i++)
{
if(A[i] < pivot)
{
s += 1;
swap(A[s], A[i]);
}
}
swap(A[l], A[s]);
return s;
}
public void swap(int i, int j)
{
int holder = A[i];
A[i] = A[j];
A[j] = holder;
}
int LinearSearch(int kthSmallest, int sizeOfA)
{
term = A[0];
for(int i=1; i<sizeOfA; i++)
{
if(kthSmallest == 1)
{
if(term > A[i])
{
term = A[i];
}
}
else
{
if(term < A[i])
{
term = A[i];
}
}
}
return term;
}
}
public class KthDriver
{
public static void main(String[] args)
{
KthSmallest k1 = new KthSmallest();
int[] array = {7,1,5,9,3};
System.out.print(k1.SelectionRecursive(array, 3, array.length));
}
}
Inside your LomutoPartition method, you are passing the array elements in your swap method: -
swap(A[s], A[i]); // Inside for loop
and
swap(A[l], A[s]); // Outside for loop
And your swap method considers them as indices: -
public void swap(int i, int j) <-- // `i` and `j` are elements A[s] and A[i]
{
int holder = A[i]; <-- // You are accessing them as indices(A[i] -> A[A[s]])
A[i] = A[j];
A[j] = holder;
}
That is why you are getting that exception. Because, if any element in array is greater than size, it will blast out.
You should change your invocation to: -
swap(s, i); // Inside for loop
and
swap(l, s); // Outside for loop
respectively. And leave your method as it is.
Note that, you should pass array indices, and not array elements. If you pass array elements, then the swapping in the method will not be reflected in your array. Because, your method will have its own copy of your elements.

Categories

Resources