My code asks a user to enter an amount of temperatures and prints out the average, then sorts the temperatures in ascending order and descending order. For ascending order I've used selection sort and for descending order I've used bubble sort. My problem is that when I use bubble sort, the last sorted element does not print and I'm not sure why it's doing this. What am I doing wrong?
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.println("How many temperatures?");
int size=keyboard.nextInt();
int temp[]=new int[size];
System.out.println("Please enter "+temp.length+" temperatures");
double sum=0;
for(int i=0;i<temp.length;i++){
temp[i]=keyboard.nextInt();
sum=sum+temp[i];
}
double average=sum/temp.length;
System.out.println("The average temperature is: "+average);
System.out.println(" ");
System.out.println("Selection sort algorithm for ascending order");
int min;
for (int i = 0; i < temp.length; i++) {
min = i;
for (int j = i + 1; j < temp.length; j++) {
if (temp[j] < temp[min]) {
min = j;
}
}
if (min != i) {
int temporary_var = temp[i];
temp[i] = temp[min];
temp[min] = temporary_var;
}
System.out.print(temp[i]+ " ");
}
System.out.println("");
System.out.println("Bubble sort algorithm for descending order");
for(int i=0; i<temp.length-1; i++)
{
if(temp[i]>temp[i+1])
{
int temporary_var = temp[i ]; //swap elements
temp[i] = temp[ i+1 ];
temp[i+1] = temporary_var;
}
System.out.print(temp[i]+" ");
}
}
}
You are printing in the sorting loop which is for(int i=0; i<temp.length-1; i++) having length-1. That is why it does not print the last element. Change it to for(int i=0; i<temp.length; i++) since you already have a < than operator.
I don't believe Your bubble sort algorithm is correct. Just one loop and swapping? it's just one pass of bubble sort and that won't sort the array for you.
First correct your algorithm and then output the numbers outside loop
Here's the correct code for bubble sort
for(int k=0; k<temp.length; k++)
{
for(int i=0;i<temp.length-1;i++)
{
if(temp[i]>temp[i+1])
{
int temporary_var = temp[i ]; //swap elements
temp[i] = temp[ i+1 ];
temp[i+1] = temporary_var;
}
}
//print array here
Your bubble sort's print statement is part of a for loop that only reaches an index of length minus 2. On zero indexed arrays the last index is length - 1.
Related
So, like the question says I want to arrange the occurrences of these elements in an ascending order of those elements. For example- if I input 7-3 times and 3-2 times, then output should be printed with 3-2 first and then (next line) 7-3. If you see the for loop with the comment to sort through the array, without that for loop the code works fine but doesn't print the elements in an ascending order. Let me know what you think about this and why that for loop isn't working?
#include<stdio.h>
int x;
int main()
{ int a[10000],b[10000],i,j,n,x,c=0,p,q ;
scanf("%d",&n);
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
for(i=0; i<n; i++)
{ c=1;
if(a[i]!=-1)
{ for(j=i+1; j<n; j++)
{
if(a[i]==a[j])
{ c++;
a[j]=-1;
}
}
b[i]=c;
}
}
for (i = 0; i < n; ++i) \\for loop to sort a[i] elements in ascending order
{ for (j = i + 1; j < n; ++j)
{
if (a[i] > a[j])
{
x = a[i];
a[i] = a[j];
a[j] = x;
}
}
}
for(i=0; i<n; i++)
{
if(a[i]!=-1 && b[i]>1)
{
printf("%d-%d\n",a[i],b[i]);
}
}
return 0;
}
You can do it either in O(n * lg n) e.g. using sorting or in expected linear time using std::map, I'm not sure if there is something like this in C.
Example impl. w/ sorting:
#include <iostream>
#include <vector>
#include <algorithm>
std::vector<int> v = {3,7,7,7,3,7,7};
std::sort(v.begin(), v.end());
for (int i = 0; i < v.size(); ++i) {
int number = v[i];
int count = 1;
while (v[i + count] == number) ++count;
i = i + count;
std::cout << number << " " << count << std::endl;
}
If you know that range of elements in the array is small enough you can use radix sort and so get it done in linear time.
About your implementation.
You are good with the first loop.
In the second loop, you need to take into account -1 entries. Also you need to swap not only a but b entries as well.
Check for b[i] equals to 1. You can initialize it to 0 before c=1; and drop b[i] > 1 check.
Few more comments not related to correctness. Do not use magic number -1, give it a name, and then use it. Do not declare all variables at the beginning of the function, declare every variable as close as possible to the first use.
I search everywhere on the internet for the best case time complexity of selection sort that is o(n^2). But i write and tested this below code of selection sort that can work in O(n) for best case (that is array is already sorted). Please find the mistake in this program
This is my code:
#include <bits/stdc++.h>
using namespace std;
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, max_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n - 1; i++)
{
cout << endl;
printArray(arr, n);
// Find the minimum element in unsorted array
max_idx = 0;
int count = 0;
for (j = 1; j < n - i; j++)
{
if (arr[j] >= arr[max_idx])
{
max_idx = j;
count++;
}
}
if (count != n - i - 1)
{ //swap only if not already sorted
// Swap the found minimum element with the first element
swap(&arr[max_idx], &arr[n - i - 1]);
}
else //already Sorted so returning
{
return;
}
//cout << "Sorted array: \n";
printArray(arr, n);
}
}
// Driver program to test above functions
int main()
{
int arr[] = {2, 1, 4, 3, 6, 5, 8, 7};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}
// This is code is contributed by www.bhattiacademy.com
Yes, your algorithm has a best case running time of Θ(n), because if the array is already in ascending order then count will equal n - 1 on the first iteration of the outer loop, so the algorithm will terminate early.
Your algorithm is different to the standard selection sort algorithm, which looks like this:
for(int i = 0; i < n - 1; i++) {
int min_idx = i;
for(int j = i + 1; j < n; j++) {
if(arr[j] < arr[min_idx]) {
min_idx = j;
}
}
swap(&arr[i], &arr[min_idx]);
}
The selection sort algorithm iteratively searches for the minimum remaining element and swaps it into place. This doesn't create an opportunity to detect that the array is already in increasing order, so there's no opportunity to terminate early, and selection sort's best case running time is therefore Θ(n2).
Selection Sort: Idea Given an array of n items
1.Find the largest item x, in the range of [0…n−1]
2.Swap x with the (n−1)th item
3.Reduce n by 1 and go to Step 1
Selection sort function you can use following algorithm has hint to write the code:
Selection Sort:
I have created a selection sorting algorithm but someone said to me its not right selection sort.
If its not right so what type of sorting is it? and how it is different then selection sorting.
Code:
void selection_Sort(int arr[] , int size){
int temp , length = size;
for(int i = 0; i < size ; i++){
for(int j = i + 1; j < size ; j++){
if(arr[i] > arr[j]){
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
please tell me how can i improve it?
To transform this code into selection sort, you have to find index of minimal element in the inner cycle, and exchange element at this index with i-th element after inner cycle finishes.
So overall number of swaps does not exceed N (while your current code could produce about N^2/2 swaps)
You have implemented Bubble sort.
The selection sort means you should find the lowest(or bigest) element in inner cycle and then switch it with element to the left/right which is at the edge of selecting (like in the picture).
There are three similar sorting alghoritms - select sort, insert sort and bubble sort you can watch how they behave here : http://i.imgur.com/fq0A8hx.gif
You have to implement a minimum element after outer for loop.
Here is the code:
def selectionSort(arr):
for i in range(len(arr)):
# Find the minimum element in remaining
# unsorted array
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j]:
min_idx = j
# Swap the found minimum element with
# the first element
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
arr = [7,4,5,9,8,2,1]
print(selectionSort(arr))
How Selection sort works?
Starting from the first element, we search the smallest element in the array, and replace it with the element in the first position.
We then move on to the second position, and look for smallest element present in the subarray, starting from index 1, till the last index.
We replace the element at the second position in the original array, or we can say at the first position in the subarray, with the second smallest element.
4.This is repeated, until the array is completely sorted.
Selection Sort in Javascript
Comparing each with the rest and swapping with the smallest from the rest
Try this code here: https://repl.it/#VinitKhandelwal/selection-sort-javascript
function selectionSort(arr){
let min;
let i;
let j;
let temp;
console.log("Input Array");
console.log(arr);
for (i = 0; i < arr.length-1; i++) {
min = i;
for (j = i+1; j < arr.length; j++) {
console.log(arr[i], arr[j]);
if (arr[j] < arr[min]) {
console.log(arr[j]);
min = j;
}
}
if (min !== i) {
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
console.log(arr);
}
}
console.log("Sorted using Selection Sort");
return arr
}
console.log(selectionSort([5,7,6,9,8,2,1,4,3]));
// console.log(selectionSort([1,2,3,4,5,6,7,8,9])); // uncomment to try best case, i.e. sorted
var Selectionsort = function (A) {
for (var i = 0; i < A.length; i++) {
var imin = i;
for (var j = i + 1; j <= A.length; j++) {
if (A[j] < A[imin])
imin = j;
}
var tmp = A[i];
A[i] = A[imin];
A[imin] = tmp;
}
return A;
};
var A = [10, 20, 30, 40, 50, 60, 70, 80];
var Aftersorted = Selectionsort(A);
console.log(Aftersorted);
You can improve it this way:
void selectionSort(double array[], int size) {
int min;
double temp;
for (int step = 0; step < size-1; step++) {
min = step;
for (int i = step+1; i < size; i++) {
if (array [i] < array[min]) {
min = i;
}
}
temp = array[step];
array [step] = array[min];
array [min] = temp;
}
Selection Sort in C
Selection sort is basically selecting the very first element of your unsorted sub-array as a minimum and comparing it with the other elements of your sub-array to find your original minimum. Then, replacing that minimum element with the first element of your sub-array. That's all!
Here goes my code...
#include <stdio.h>
void selectionSort(int n){
int arr[n],i,j,minIndex;
printf("\nInsert %d elements:\n",n);
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
printf("Insert complete.\n\n");
printf("Your array looks like:\n");
for(i=0;i<n;i++){
printf("%d ",arr[i]);
}
//Selection Sort Algorithm
for(i=0;i<n-1;i++){
minIndex = i;
for(j=i+1;j<n;j++){
if(arr[j] < arr[minIndex]){
minIndex = j;
}
}
//Swapping elements
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
printf("\n\nAfter sorting your array looks like:\n");
for(i=0;i<n;i++){
printf("%d ",arr[i]);
}
}
int main(){
int n;
printf("Enter number of array elements: ");
scanf("%d",&n);
selectionSort(n);
return 0;
}
Result: -
Given the algorithm for Bubble Sort:
Algorithm BubbleSort(A[0...n]):
for i <- 0 to n-2 do
for j <- 0 to n-2-i do
if(A[j+1] < A[j] then swap(A[j], A[j+1]))
I have to rewrite the Bubble Sort algorithm using where we "Bubble Up" the smallest element to the ith position on the ith pass through the list.
Can anyone help me with this?
Currently you are traversing the array from the start, therefore if you come upon the largest element, it will be "Bubbled up" to the end of the array. If you want to do the opposite, "Bubbling down" the smallest element to the start, you need to traverse the array in the opposite direction, from the end to the start. Hope it helps you to find the way.
#include<stdio.h>
void bubbleSort(int *x,int size)
{
int e,f,m,g;
m=size-2;
while(m>0)
{
e=0;
f=1;
while(e<=m)
{
if(x[f]<x[e])
{
g=x[e]; //swaping
x[e]=x[f];
x[f]=g;
}
e++;
f++;
}
m--;
}
}
void main()
{
int x[10],y;
for(y=0;y<=9;y++) //loop to insert 10 numbers into an array
{
printf("Enter a number: ");
scanf("%d",&x[y]);
}
bubbleSort(x,10); //pass number entered by user and size of array to bubbleSort
for(y=0;y<=9;y++) //loop to print sorted numbers
{
printf("%d\n",x[y]);
}
}
Looks like the answer to this has not been accepted yet. Hence trying to check if this is still an issue.
Here is what I think can be a possible implementation in Java. As #Warlord mentioned, the algorithm is to ensure that the array in concern for sorting is imagined as a vertical array. With each pass, all we are doing is check if there is a larger element below and if found that element is bubbled up to the top.
static void bubbleUpSort(int[] arr){
final int N = arr.length;
int tmp = 0;
for (int i=0; i < N; i++){
for (int j=N-1; j >= i+1; j--){
if (arr[j] < arr[j-1]){
tmp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = tmp;
}
}
}
for (int k =0; k < arr.length; k++){
System.out.print(arr[k] + " ");
}
}
Called from main as:
public static void main(String[] args) {
System.out.println("Bubble Up Sort");
int[] bUp = {19, 2, 9, 4, 7, 12, 13, 3, 6};
bubbleUpSort(bUp);
}
Bubble Sort
Comparing each with the neighbor and swapping if first is greater than the next
function bubbleSort(arr){
let temp;
console.log("Input Array");
console.log(arr);
for (let i = 0; i < arr.length-1; i++) {
for (let j = 0; j < arr.length-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
console.log(arr[j],"swapped with",arr[j+1])
console.log(arr);
} else {
console.log("SKIP");
}
}
}
console.log("Sorted using Bubble Sort");
return arr;
}
console.log(bubbleSort([7,6,9,8,2,1,4,3,5]));
I have to perform a run time analysis on quicksort by incrementing the size of the array by 100 each time. However when I measure the runtime using System.nanoTime the results aren't as I expect (my graphs look more like O(2^n)). The time shoots up whenever the array reaches around 800. Could someone please tell me where I'm going wrong with my code.
Also the count part is sort of irrelevant at the moment, since i only want to run the quicksort once at each array size.
import java.util.Random;
public class Quickworking {
public static void main(String[] args) {
Random rand = new Random();
int count2;
long total = 0;
count2 = 1;
int [] myArray = new int[1400];
//generates random array
for (int i = 0; i < myArray.length; i++){
myArray[i] = rand.nextInt(100) + 1;
//System.out.print(myArray[i] + ", ");
}
//loop sort n amount of times
for (int count = 0; count < count2; count++){
//calls the sort method on myArray giving the arguments
long start = System.nanoTime();
sort( myArray, 0, myArray.length - 1 );
long end = System.nanoTime();
System.out.println(end - start );
total += (end - start);
}
//long average = (long) total / (long) count2;
//System.out.println(average);
//prints the sorted array
//for (int i = 0; i <myArray.length; i++){
// System.out.print(myArray[i] + ", ");
//}
}
public static int sort(int myArray[], int left, int right){
int i = left, j = right;
int temp;
int pivot = myArray[(left + right) / 2];
//System.out.println("here are the pivot numbers " + pivot + ", ");
if (i <= j){
while (myArray[i] < pivot) //&& (i<right))
i++;
while (myArray[j] > pivot) //&& (j>left))
j--;
if (i <= j){
temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
i++;
j--;
}
}
if (left < j) sort(myArray, left, j);
if (i < right) sort(myArray, i, right);
return i;
}
}
Quicksort's behaviour when sorting already sorted arrays is O(n^2). After the array is sorted the first time in your code you are then sorting the sorted array. That will give you the worst case for quick sort. You need to generate a completely new random array each time to really test this.
QuickSort does not perform well on already sorted data.
See here:
http://en.wikipedia.org/wiki/Quicksort
You should randomize your array within the for loop in order to get more accurate results.