Python 3: def bubbleSort(alist): for passnum in range(len(alist)-1, 0, -1): for i in range(passnum): if alist[i] > alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp return alist def main(): lines = [] print("Enter names (hit enter twice to bubble-sort):") while True: line = input("%3i: " % (len(lines)+1)) if...
c++,xcode,debugging,function-pointers,bubble-sort
The function prototype of ArraySorter takes (int, int, pfPointer), but the function definition takes (int [], int, pfPointer). Change the prototype of ArraySorter to take (int [], int, pfPointer), and the change the calls to ArraySorter to ArraySorter(pnArray, nArraySize, Descending) rather than ArraySorter(pnArray[nArraySize], nArraySize, Descending)....
c,segmentation-fault,bubble-sort
Using sizeof to get the size of array is tricky in C, that it only gives you the right answer when applied to the original array. For example, int array[10]; int len = sizeof(array); // => 10 * sizeof(int) However when applied to a pointer, as you did in your...
c,bubble-sort,doubly-linked-list
It's not clear what your C level expertise is. Some of the below is fairly basic and not all issues are covered. Please ask further if required. Most data structures would make use of pointer and the C struct construct. For example, a doubly linked list node in your case...
java,sorting,calendar,bubble-sort
If you do not need to sort your list by a bubble sort, then you can use java.util.Collection.sort(). Your code will become : Collections.sort(list); You need however to make Your class (Note if I am right) implement Comparable or to create a comparator. Here you can find some examples....
sorted is a Boolean variable that is used to indicate whether the sort is complete or not. Initially, sorted is set to false (assuming that the array is not yet sorted). The entry condition on the main (outer) loop checks whether sorted is true or false, and, as you can...
The problem, as expected, comes in method sort(): public void sort() { if (size > 1) { for (int i = 0; i < size; i++ ) { Node currentNode = head; Node next = head.nextNode; for (int j = 0; j < size - 1; j++) { if (currentNode.data...
c,sorting,placeholder,ternary-operator,bubble-sort
You cannot do it this way. But you can write an expression that will do a conditional comparison: if (is_ascending ? ptr->next->value < ptr->value : ptr->next->value > ptr->value) ... If is_ascending is guaranteed to be 0 or 1, here is an alternative with a single test that may be faster:...
c,arrays,computer-science,bubble-sort,c-strings
Arrays are not assignable as you're attempting in C. You need to setup some buffer swapping logic. For example. if(strcmp(str[j+1],str[j]) < 0) // note: fixed. { strcpy(temp, str[j]); strcpy(str[j], str[j+1]); strcpy(str[j+1], temp); } Other issues with your code: Incorrect size of your input array. All those strings require at least...
Arrays decays to pointers, so your comparison S[j].name>S[j+1].name is comparing pointers and not the strings. If you want to compare string you need to use either std::string instead of character arrays, or use strcmp....
javascript,html,algorithm,bubble-sort
You have an error in your code: if (ii = len) { and also if (swapped = 1){ it should be double equal...
If I understand you correctly, I would suggest the following: What you would need to do is to compare the Integer values of the array: if(Integer.valueOf(2dArray[i][0]) < Integer.valueOf(2dArray[i-1][0])){ The reason you don't include j is because you are only sorting by the value of the first column. 2dArray[i][0] gets you...
To do this in a single pass requires a differentiation of digits and non-digits. Once you have that, the algorithm can be summed up as: Always swap if you have digit in the first slot and a non-digit in the second. Else, only swap if their both digits or both...
Try this html code. <!doctype html> <html> <head> <meta charset="utf-8"> <title>Submit a Ticket</title> <style type="text/css" media="screen"> .hidden { display: none; } </style> </head> <body> <form name="form1" id="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>"> <h5>Bubble Sort</h5> <h6>Fill the values</h6> <label>Value 1<input type="text" name="bubble_values[]" id="bubble_values1" size="10"...
You cannot strcmp a NULL value. Although you are guarding against a strcmp of people[j+1] being NULL, you don't check people[j]. Try the following (untested), which simply provides a strcmp function which treats a NULL like "". int strcmpwithnull(const char *a, const char *b) { return strcmp(a?a:"", b?b:""); } void...
java,arrays,bubble-sort,method-call
public static void main(String[] args) { BubbleSort bs = new BubbleSort(); //name of your class instead of BubbleSort double[] r1Array = {intJ1R1, intJ2R1, intJ3R1, intJ4R1, intJ5R1, intJ6R1}; double[] r2Array = {intJ1R2, intJ2R2, intJ3R2, intJ4R2, intJ5R2, intJ6R2}; double[] sortedR1 = bs.bubbleSort(r1Array); double[] sortedR2 = bs.bubbleSort(r2Array); } public double[] bubbleSort(double[] array){...
c++,sorting,structure,bubble-sort
Your code won't compile in its current state since you reference 'size' and 'array' variables that do not exist, but here's what a bubble sort looks like: void sortArray(incomeInfo income[], int count) { for (int i = 0; i < count; i++) for (int j = 1; j < count;...
What I want to ask is my code is an example of bad programming or not? Your code almost is identical. There is a difference in that you are (correctly) using curly brackets to explicitly state code blocks, while the other example isn't. One problem is your loop bounds...
java,algorithm,bubble-sort,selection-sort
Well, as I see in your code, the number of iterations in both algorithms will be the same for(int i=0;i<list.size();i++) for(int j=i+1;j<list.size();j++) would be the same as for(int i=list.size()-1;i>0;i--) for(int j=0;j<=i-1;j++) so the difference should rely on what's happening inside each iteration (I will just be taking the inner part...
If you are looking for code which will take input from the user, it will be something like following: puts "Enter Number of Elements" n = gets.chomp puts "Enter #{n} elements" n.to_i.times do (arr ||= []) << gets.chomp end ...
c,segmentation-fault,bubble-sort
Change sizeof(data) In the condition of all the for loops to sizeof(data)/sizeof(data[0]) This is done because sizeof(int-array) is the number of elements in the array multiplied with the sizeof(int)(which is usually 4 bytes). sizeof(data[0]) is the same as sizeof(int) as data[0] is an int. So, you can also use sizeof(data)/sizeof(int)...
Not sure if your algorithm is correct, but here is the standard way to swap. If you're sorting a String array you will also need to get the numerical value (I assume the Strings contain numbers?). Also just noticed you will get an array out of bounds exception, start at...
You just need to declare aray as a char instead of an int. I'd recommend a clearer variable name as well: foreach (char ch in letters) Console.Write(ch + " " ); Also, why not just declare letters as a char[] and t as a char? char[] letters = { 'c',...
You need to pass by reference; by making a copy, you sort a temporary copy, and then that's it; it disappears and the original is still unsorted, because, once again, you sorted only a temporary copy of the entire vector. So change vector<int> a to vector<int>& a. Here's the code,...
Your code is fine. To make sure every pass is printed then simply print the pass at the start of the loop. Also you don't need to declare additional variables to keep track of pass. for (i = 0; i < (s - 1); i++) { printf("\nAfter Pass %3d elements...
Why is it called bubble sort? The bubble sort gets its name because elements tend to move up into the correct order like bubbles rising to the surface. ...
javascript,arrays,sorting,for-loop,bubble-sort
There are several reasons why your attempt didn't work, but there is a fundamental flaw in your assumption: the order of properties in an object is undefined, so you should not try to rearrange them. There's really no reason to use sorting for this. Just go through the object once...
c,arrays,sorting,search,bubble-sort
You had several compilation errors, below I rewrote your code with comments so that it can compile. The actual functions seem to work just fine The most important change was passing array to both functions. It is passed as int* so that the functions can modify array in the context...
Take a look at Python's built-in methods and functions: raw_input and split. def bubbleSort(alist): for passnum in range(len(alist)-1,0,-1): for i in range(passnum): if alist[i]>alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp alist = raw_input('Enter the list to sort (seperated by spaces): ').rstrip() alist = alist.split(' ') bubbleSort(alist) print(alist)...
java,algorithm,sorting,comparator,bubble-sort
Your code looks little bit strange. You didnt mention if you have to use bubble sort so i write both my ideas 1.Without explicitly using bubble sort You can use Collections.sort() combined with overridencompareTo() method So your code will look like this class Student implements Comparable<Student>{ //variables constructor methods go...
boolean,pascal,long-integer,bubble-sort,insertion-sort
In Pascal, boolean operators and and or have higher precedence than the comparison operators >, =, etc. So in the expression: while j > 0 and A[j] > key do Given that and has higher precedence, Pascal sees this as: while (j > (0 and A[j])) > key do 0...
c,arrays,sorting,char,bubble-sort
I have no idea why there are quotes around the array elements, but that is not doing what you think, the comparison is happening because a multicharacter string is evaluated to an integer value which is implementation defined, hence the if statement is always comparing the same values, which means...
Let's break down each piece of the method. The first part of the code to understand is the inner most block: int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; If we were to run the above statements on the array {1,2,3,4,5}, with j=2, We...
There are some errors in your code. First, the algorithm: $holder = $integers[$j]; if ($integers[$j] < $integers[$j-1]){ $integers[$i] = $integers[$j-1]; $integers[$j-1] = $holder; } The second assignment above should read: $integers[$j] = $integers[$j-1]; because you are swapping $integers[$j] with $integers[$j-1] if they are in the wrong order (I am sure...
c++,arrays,sorting,structure,bubble-sort
This swap is wrong: temp = student_database[i]; student_database[i] = student_database[i + 1]; student_database[i] = temp; You change student_database[i] but then reassign it to its previous value. You're supposed to update student_database[i + 1]. student_database[i + 1] = temp; Better to use std::swap() anyway: std::swap(student_database[i], student_database[i + 1]); ...
java,algorithm,optimization,foreach,bubble-sort
Using indexOf is not correct, if your ArrayList x contains more than one value of i, your sort method will behave incorrectly. For example, this case: [5, 5, 1] After running your program, return [5, 5, 1] Plus, using indexOf, as mentioned by tucuxi, will slow down your program....
c,arrays,recursion,quicksort,bubble-sort
Either use a global variable as suggested in the comments : int _SwapCount = 0; void quicksort(int arr[],int first,int last) { ... //whenever you swap _SwapCount++; or take a pointer to an int as a parameter: void quicksort(int arr[],int first,int last, int* swapCount) { ... //whenever you swap (*swapCount)++; //recursion...
java,android,string,bubble-sort
If bubble sort is the answer you must have misunderstood the question. I strongly recommend you just add ORDER BY announcementId to the end of your query. That way the database will sort by your column for you. Edit You could use ORDER BY 1 to sort by the first...
c++,arrays,sorting,bubble-sort
You don't initialize X before you use it to index the array. And then you never increment X after reading data into the array, so all your input numbers are being stored in the same location. Each one wipes out the memory of the one that was read before it....
All it's doing is swapping two entries in an array. arr[i] is being set to the current value of arr[i+1] and at the same time arr[i+1] is being set to the current value of arr[i]. It's called multiple assignment or parallel assignment. So to take your example: say in this...
From Intel's manual: The terms “above” and “below” are associated with the CF flag and refer to the relation between two unsigned integer values. The terms “greater” and “less” are associated with the SF and OF flags and refer to the relation between two signed integer values By using jb...
In some of the old C compilers, you can't compare characters. A simple solution would be type-casting. As for your code, main() { int n,j,k; char a[20], temp; //statements to scan the number of items (n) and the string a[n]. for(j=1; j<n; j++) { for(k=0; k<n-j; k++) { if((int)a[k]>=(int)a[k+1]) {...
You can use Collection.sort(). for sorting any kind of ArrayLsit Object. Collections.sort(listOfStringArrays,new Comparator<String[]>() { public int compare(String[] strings, String[] otherStrings) { return strings[1].compareTo(otherStrings[1]); } }); ...
Use strcmp if(strcmp(Strings[i], Strings[i+1]) > 0) { //swap elements } it will basically compare chars in strings and first not matching pair of chars, if it has greater value in first string passed to function, it will return 1....
c,sorting,linked-list,bubble-sort
After the for,before restarting the while, you have to set current and nextElement pointing the beginning of the list! Or they dont change and the test condition of the for fail immediatly. Also, what's the point of the mallocs? you use current,next and temp only as pointer to node, not...
java,arrays,sorting,bubble-sort
If you really have to do it like that you could just add another temp variable and swap the items in names at the same time you swap the results. ie. just duplicate the first 3 lines in the if statement. But it would be better to make a Player...
put swapped = 0 before the for-loop, not inside it, and fix the string comparison as per other answers.
algorithm,sorting,big-o,bubble-sort
This case is much harder than the algorithm with two for loops, as the exact number of iterations of the outer loop does not depend just on N, but also on the particular arrangement of the data. If the array is initially sorted, there will be no swaps at all...
c++,sorting,vector,return,bubble-sort
If you don't need, there is no need to return, you can have return type as void void b_sort(sample &s){ .. }//return nothing ...
java,arrays,recursion,bubble-sort
You mention in the comments that you've already solved bubblesort. So I'm going to assume you have a method with the signature void bubbleSort(int[] arr). Your code shows you understand how to acquire an array from the user, so we don't need to handle that. Now what you're describing is...
java,arrays,command-line-arguments,bubble-sort
You can't initialize arr before you parse the user input. The statement public int[] arr= new int[input]; results with an array of size 0 so any attemt to access it will throw an exception. Try initializing the array inside the main, after parsing the array length.
You need to parameterize BubbleSort and use an array of a reference type, not a primitive type (since generics only works with reference types): Double[] A = { 3d, 2d, 4d, 6d, 7d, 1d, 2d, 3d }; // notice Double ref. type BubbleSort<Double> bs = new BubbleSort<Double>(A); // notice <Double>...
python,python-2.7,sorting,bubble-sort
The result of raw_input().split() is a list of strings, not integers. Your algorithm is correct -- you're sorting the strings in alphabetical order. A quick fix is to use e.g. bubbleSort(input(), [int(x) for x in raw_input().split()]) ...
It does not go to last element because the next pointer of last element is NULL , You need to make "j!=nullptr;" You compare theese guys with themselves (it is not cause of your problem but it does not seem cool :D ) If you want to fix it, make...
c#,properties,stack-overflow,bubble-sort,generic-list
public List<Person> TheList { get { return TheList; } set { TheList = value; } } This setter refers to itself. Any attempt to read or write to it will cause an infinite recursion....
c++,string,exception-handling,bubble-sort
#include<iostream> #include<conio.h> using namespace std; int main() { int hold, swapNumber = 0, compare = 0, array[10]; const string Error = "Error! ONLY INTEGER INPUT ALLOWED!"; cout << "Enter 10 numbers: " << endl; try { for ( int i = 0; i < 10; i++ ) { cin >>...
c,sorting,linked-list,bubble-sort
It's a double-linked list. To swap two nodes, typically 6 pointers need to be updated. Say we have A <-> B <-> C <-> D and you want to swap B and C: you'll need to update right of A, B, and C, and also left of B, C, and...
You just have to change the swapping procedure (the innermost block of code) like this and remove the int temp = 0 line at the beginning: var temp = taskStructure.TasksArray[sort + 1]; taskStructure.TasksArray[sort + 1] = taskStructure.TasksArray[sort]; taskStructure.TasksArray[sort] = temp; But note, you can also use the Array.Sort method like...
When you are comparing the values. You also compare the last one, with the first one outside the array. This happens to be 0(undefined behaviour,totally dependent on compiler) and gets switched in. The for-loop should become: for (p=0;p<10;++p) { for(t=0;t<9;++t) { if(num[t]>num[t+1]) { temp=num[t]; num[t]=num[t+1]; num[t+1]=temp; } } } ...
This is effectively a bubble sort. The interviewer might have wanted to hear about some well known, more efficient algorithms like Quicksort. If you are going to an interview, be prepeared with well known algorithms, do no invent your own! Also when you argue about run time of an algorithm,...
c#,bubble-sort,indexoutofrangeexception
private void button1_Click(object sender, EventArgs e) { int sizeOfArrayInt = Convert.ToInt32(arraySize.Text); int[] array = new int[sizeOfArrayInt]; string numbers = arrayValues.Text; string[] numbersSplit = numbers.Split(','); int count = 0; foreach (string character in numbersSplit) { int value; bool parse = Int32.TryParse(character, out value); if (value != null) { array[count] =...
algorithm,sorting,c#-4.0,bubble-sort
Try this version of Bubble Sort. public void BubbleSort() { int temp; for (int outer = 0; outer < upper - 1; outer++) { for (int inner = 0; inner < upper - outer; inner++) { if (arr[inner + 1] < arr[inner]) { temp = arr[inner + 1]; arr[inner +...
java,arrays,sorting,bubble-sort,parallel-arrays
Your problem is here: if (storeItem[x - 1] > storeItem[x] && itemPrice[x - 1] > itemPrice[x]) you are only moving items if both the item and the price is greater - this is not a proper sort. Imagine data such as: 5,10 1,20 These will not be swapped - and...
You should use separate variables in inner and outer loops. Using y in inner loop instead will give you the correct answer. var bubbleSort = function (elements) { //Loop through to the second to last index. By the time we get to the last index, its already //been compared with...
python,python-2.7,checksum,bubble-sort
The issue is with your way of calculating Checksum. It fails when the array has numbers with more than one digit. For example: 2 96 7439 92999 240 70748 3 842 74 706 4 86 7 463 1871 7963 904 327 6268 20955 92662 278 57 8 5912 724 70916...
On first glance, it looks like you're leaving Book objects in the same position in the array, and just swapping the titles or authors (depending on the sort function) and leaving the remaining member the same. You should be swapping the objects themselves e.g.: void sortByAuthor(int count, string name) {...
A C++ program starts out fairly blank, without any function to use at all except for main. (There is more to say on that. I'm sure comments are going to point that out. ;)) You include headers for <iostream> and string, so you can use all of the functions declared...