quicksort doesn't sort string with many letters - java

I've been trying to do a program that sorts characters from a string in alphabetical order.
It works with short words, but when I tried to input word such as : abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz. It doesn't sort it at all.
Can somebody help me to improve my code?
Here is my code:
public class quicky{
public static void partition(char[] a,int low, int high){
int i = low;
int j = high;
char tmp;
int pivot = i+(j-i)/2;
while (i <= j) {
while(a[i] < a[pivot]){
i++;
}
while(a[j] > a[pivot]){
j--;
}
if(i <= j) {
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
}
if(low < j){
partition(a, low, j);
}
if(i < high){
partition(a, i,high);
}
}
public Character[] toCharArray( String s )
{
int len = s.length();
Character[] array = new Character[len];
for (int i = 0; i < len ; i++) {
array[i] = new Character(s.charAt(i));
}
return array;
}
public static void main(String[] args)
{
String input = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
String output = quicksort(input);
System.out.print(output);
}
public static String quicksort(String y)
{
int length = y.length();
int i = 0;
int j = length-1;
char[] a = y.toCharArray();
partition(a,i,j);
String x=new String(a);
return x;
}
}

Related

Method to find second highest number in an array in java

Getting output of 0 each time when im ment to get 3 looked over my code my not sure where i have gone wrong i can do it without using a method i know but just trying to practice java
public class App {
public static int second(int a[],int n) {
int[] arr = new int [n];
int temp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
public static void main(String[] args) {
int[] arr = {1,3,2,5,3};
int n = 5;
int result = second(arr,n);
System.out.println(result);
}
}
You could change the array parameter name arr and remove the declaration or copy the values from a to arr.
public static int second(int arr[],int n) {
int temp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
The reason you get zero is because the primitive int cannot be null. So, when you create the array of length 5, it starts out filled with zeroes.
Doing it by using streams:
public static int second(int a[]) {
return Arrays.stream(a)
.sorted()
.skip(a.length - 2)
.findFirst()
.getAsInt();
}
I removed the second argument. It sorts your array and skips all the elements prior to the one you want, before picking the now first element.
public static int second(int[] arr) {
int highest = arr[0];
int second = 0;
for (int i = 1; i < arr.length; i++) {
int j = arr[i];
if (j >= highest) {
highest = j;
} else if (j > second) {
second = j;
}
}
return second;
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 5, 3};
int result = second(arr);
System.out.println(result);
}
Here is one way that doesn't require sorting.
int[] arr = { 10, 2, 3, 19, 2, 3, 5 };
System.out.println(second(arr));
prints
10
set largest to the first value in the array
set secondLargest to the smallest possible
now iterate thru the array.
if the current value is greater than largest:
replace secondLargest with Largest
replace largest with current value
else check to see if current value is greater than secondLargest and assign if true.
public static int second(int arr[]) {
int largest = arr[0];
int secondLargest = Integer.MIN_VALUE;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
public static int second(int arr[],int n) {
int temp;
if(arr.length < 2) {
return -1;
}
else {
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {23,14,56,77,66,67};
int high = 0;
int sec = 0;
for(int i = 0 ; i <a.length; i++){
if(high < a[i]){
sec = high;
high = a[i];
}
else if(sec < a[i]){
sec = a[i];
}
}
System.out.println("the first highest number is " + high);
System.out.println("the second highest number is " + sec);
}
}
public static int sec(){
int arr[] = {12,3,67,4,5,65};
int high = 0;
int low = 0;
for(int i = 0 ; i < arr.length ; i ++){
if(high < arr[i]){
low = high;
high = arr[i];
}
else if(low < arr[i]){
low = arr[i];
}
}
return low;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
sch obj = new sch();
int a = obj.sec();
System.out.println(a);
}
}
package com;
public class FindSecondHighestNumberInArray {
public static void main(String[] args) {
int []arrayOfIngeger = {-23,-989,-878,-2,-5,-3,-4,-123,-345,-98,-675,-98};
int highestNumber = arrayOfIngeger[0];
int secHighestNumber = 0;
for(int i = 1; i < arrayOfIngeger.length; i++ ) {
if(highestNumber < arrayOfIngeger[i]) {
secHighestNumber = highestNumber;
highestNumber = arrayOfIngeger[i];
}else if(secHighestNumber < arrayOfIngeger[i] && arrayOfIngeger[i] != highestNumber) {
secHighestNumber = arrayOfIngeger[i];
}
}
System.out.println("second Highest Number in Array : "+secHighestNumber);
}
}

What is time complexity of this recursive function?

public static int[] index(int input[],int x,int i){
if (i==0) {
if (input[i]==x)
return new int[] {0};
else
return new int[] {};
}
int[] c = index(input, x, i-1);
if (input[i] == x) {
int len = c.length + 1;
int[] a = new int[len];
int j;
for (j = 0; j <= c.length - 1; j++)
a[j] = c[j];
a[j] = i; // j++
return a;
}
return c;
}
What is time complexity of this recursive function which returns all indices of occurrence of an element x in an input array?

Java ArrayIndexOutOfBoundsException MOOC Helsinki - where is the mistake in my code?

I've been searching for an answer, but without any results. I know that this exception means that I'm trying to reach nonexistent array element, but I just can't see it.
It's excercise 104 from MOOC Helsinki, you can read it here
http://mooc.cs.helsinki.fi/programming-part1/material-2013/week-6?noredirect=1
I'm supposed to create sorting algorithm by creating five methods one after another. I've created first four, but things go south with the final one. I have no idea whether it's just matter of changing a single character, or the whole construction is flawed.
I would be grateful for help, feel free to comment on my code, but if it's possible do not overwrite the whole thing, I don't want solving it for me, just some hints and help.
import java.util.Arrays;
public class Main {
public static int smallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return result;
}
public static int indexOfTheSmallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
int result = array[index];
int position = 0;
for (int i = index; i < array.length; i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static void swap(int[] array, int index1, int index2) {
int a = array[index1];
int b = array[index2];
array[index1] = b;
array[index2] = a;
}
public static void sort(int[] array) {
int temp;
for (int x = 0; x < array.length; x++) {
System.out.println(Arrays.toString(array));
temp = indexOfTheSmallestStartingFrom(array, x);
swap(array, array[x], temp);
}
}
public static void main(String[] args) {
int[] values = {8, 3, 7, 9, 1, 2, 4};
sort(values);
}
}
change swap(array, array[x], temp); to
swap(array, x, temp);
Try this out,
import java.util.Arrays;
public class Main {
public static int smallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return result;
}
public static int indexOfTheSmallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
int result = array[index];
int position = 0;
for (int i = index; i < array.length; i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static void swap( int index1, int index2) {
int a = array[index1];
int b = array[index2];
array[index1] = b;
array[index2] = a;
}
public static void sort() {
int temp;
for (int x = 0; x < array.length; x++) {
System.out.println(Arrays.toString(array));
temp = indexOfTheSmallestStartingFrom(array, x);
swap( x, temp);
}
}
static int [] array= {8, 3, 7, 9, 1, 2, 4};
public static void main(String[] args) {
sort();
}
}
swap function was making changes but they weren't reflected because you were using pass-by-value.
I haven't touched the algorithm because the output is not as expected.

java program to print number in integer as shuffle

Sorry if my question is not clear, lets say I have int a = 1234;.
How can I print as follows, for a number of any length?
123
132
213
231
321
312
Thanks in advance.
public class Test {
private static void swap(int[] p, int i, int j) {
int t= p[i];
p[i]= p[j];
p[j]= t;
return;
}
private static boolean nextPerm(int[] p) { // need p.length > 1
int n= p.length;
int i= n;
if (i-- < 1) return false;
for(;;) {
int ii= i--;
if (p[i] < p[ii]) {
int j= n;
while (!(p[i] < p[--j]));
swap(p, i, j);
for (j= n; j > ii; swap(p, --j, ii++));
return true;
}
if (i == 0) {
for (int j= n; j > i; swap(p, --j, i++));
return false;
}
}
}
public static void main(String[] args) {
int x = 123;
String s = "" + x;
int n = s.length();
int[] p = new int[n];
for (int i = 0; i < n; i++){
p[i] = i;
}
do {
for (int i = 0; i < n; i++){
System.out.print(s.charAt(p[i]));
}
System.out.println();
}
while (nextPerm(p));
}
}
finally I found, below is the code,
class ShuffleNumber {
private static int[] a = {1,2,3};
private static void print(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(" " + a[i]);
System.out.println();
}
private static void shuffle(){
int[] b = (int[])a.clone();
for (int i = b.length - 1; i > 0; i--) {
int j = (int)Math.floor(Math.random() * (i+1));
int temp = b[j];
b[j] = b[i];
b[i] = temp;
}
print(b);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
shuffle();
}
}

Where are comparisons in java sorting methods?

Question: Where are comparisons being made in each separate sorting method?
Also if you know please tell me which method count numbers are wrong and where to place my counters instead.trying to understand where and how many times sorting methods make comparisons.
Method A B
Selection 4950 4950
Bubble 99 9900
Insertion 99 5049
Merge 712 1028
Shell 413 649
Quick 543 1041
Okay so to explain some parts, basically Array A is an array from 1-100 in ascending order. So this should be the minimum number of comparisons.
Array B is 100-1 in descending order. So I believe it should be the maximum number of comparisons. Array C is just randomly generated numbers, so it changes every time.
I feel like my selection and bubble sorts were counted correctly. Feel free to let me know where comparisons are being made that I haven't counted, or if I'm counting wrong comparisons.
Side note: Made some global variable to count the methods that were recursive in multiple sections.
class Sorting
{
static int[] X = new int[100];
static int mergecount = 0;
static int quickcount = 0;
public static void selectionSort(int list[])
{
int count = 0;
int position = 0, n = list.length;
for(int j = 0; j < n-1; j++)
{
position = j;
for(int k = j+1; k < n; k++)
{
count++;
if(list[k] < list[position])
position = k;
}
Swap(list, j, position);
}
System.out.println("counter" + count);
}
public static void Swap(int list[], int j, int k)
{
int temp = list[j];
list[j] = list[k];
list[k] = temp;
}
public static void bubbleSort(int list[])
{
int count = 0;
boolean changed = false;
do
{
changed = false;
for(int j = 0; j < list.length - 1; j++)
{
count++;
if(list[j] > list[j + 1])
{
Swap(list, j, j+1);
changed = true;
}
}
} while(changed);
System.out.println("counter" + count);
}
public static void insertionSort(int list[])
{
int count = 0;
for(int p = 1; p < list.length; p++)
{
int temp = list[p];
int j = p;
count++;
for( ; j > 0 && temp < list[j - 1]; j = j-1)
{
list[j] = list[j - 1];
count++;
}
list[j] = temp;
}
System.out.println("counter" + count);
}
public static void mergeSort(int list[])
{
mergeSort(list, 0, list.length - 1);
System.out.println("counter" + mergecount);
}
public static void mergeSort(int list[], int first, int last)
{
if(first < last)
{
int mid = (first + last) / 2;
mergeSort(list, first, mid);
mergeSort(list, mid + 1, last);
Merge(list, first, mid, last);
}
}
public static void Merge(int list[], int first, int mid, int last)
{
int count = 0;
int first1 = first, last1 = mid;
int first2 = mid + 1, last2 = last;
int temp[] = new int[list.length];
int index = first1;
while(first1 <= last1 && first2 <= last2)
{
if(list[first1] < list[first2])
{
temp[index] = list[first1++];
mergecount++;
}
else
temp[index] = list[first2++];
index++;
mergecount++;
}
while(first1 <= last1)
temp[index++] = list[first1++];
while(first2 <= last2)
temp[index++] = list[first2++];
for(index = first; index <= last; index++)
list[index] = temp[index];
}
public static void shellSort(int list[])
{
int count = 0;
int n = list.length;
for(int gap = n / 2; gap > 0; gap = gap == 2 ? 1: (int) (gap/2.2))
for(int i = gap; i < n; i++)
{
int temp = list[i];
int j = i;
count++;
for( ; j >= gap && (temp < (list[j - gap])); j -= gap)
{
list[j] = list[j - gap];
count++;
}
list[j] = temp;
}
System.out.println("counter" + count);
}
public static void quickSort(int start, int finish, int list[])
{
int count = 0;
int left = start, right = finish, pivot, temp;
pivot = list[(start + finish) / 2];
do
{
while(list[left] < pivot)
{
left++;
quickcount++;
}
while(pivot < list[right])
{
right--;
quickcount++;
}
if(left <= right)
{
temp = list[left];
list[left++] = list[right];
list[right--] = temp;
quickcount++;
}
} while(left < right);
if(start < right)
quickSort(start, right, list);
if(left < finish)
quickSort(left, finish, list);
}
public static void copy(int list[])
{
for(int i = 0; i < list.length; i++)
X[i] = list[i];
}
public static void restore(int list[])
{
for(int i = 0; i < list.length; i++)
list[i] = X[i];
}
public static void displayArray(int list[])
{
for(int k = 0; k < list.length; k++)
System.out.print(list[k] + " ");
System.out.println();
}
public static void main(String args[])
{
int[] A = new int[100];
for(int i = 0; i < A.length; i++)
A[i] = i + 1;
int[] B = new int[100];
int q = 100;
for(int i = 0; i < B.length; i++)
B[i] = q--;
int[] C = new int[100];
for(int i = 0; i < C.length; i++)
C[i] = (int)(Math.random() * 100 + 1);
displayArray(A);
copy(A);
selectionSort(A);
displayArray(A);
restore(A);
}
Note that QuickSort performance is greatly influenced by your choice of the pivot. With both of your test arrays sorted (ascending / descending) and because you are picking pivot as array[length/2] you are actually always picking the best pivot. So your test case B won't generate maximum number of comparisons for quicksort. If you were picking array[0] as pivot you'd get maximum number of comparisons for test case A and B.
The easiest way to count comparisons is to use a compare function and do it in there.
static int compareCount = 0;
int compareInt(int a, int b) {
compareCount++;
return a - b; // if 0 they are equal, if negative a is smaller, if positive b is smaller
}
Now just use compareInt in all your algorithms and you'll get an accurate count. You'll have to reset compareCount between each run though.

Categories