Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Create c++ bin sort #47

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
sarth23 wants to merge 1 commit into hustcc:master
base: master
Choose a base branch
Loading
from sarth23:patch-1
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions c++ bin sort
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#include <iostream>

using namespace std;

template <class T>
void Print(T& vec, int n, string s){
cout << s << ": [" << flush;
for (int i=0; i<n; i++){
cout << vec[i] << flush;
if (i < n-1){
cout << ", " << flush;
}
}
cout << "]" << endl;
}

int Max(int A[], int n){
int max = -32768;
for (int i=0; i<n; i++){
if (A[i] > max){
max = A[i];
}
}
return max;
}

// Linked List node
class Node{
public:
int value;
Node* next;
};

void Insert(Node** ptrBins, int idx){
Node* temp = new Node;
temp->value = idx;
temp->next = nullptr;

if (ptrBins[idx] == nullptr){ // ptrBins[idx] is head ptr
ptrBins[idx] = temp;
} else {
Node* p = ptrBins[idx];
while (p->next != nullptr){
p = p->next;
}
p->next = temp;
}
}

int Delete(Node** ptrBins, int idx){
Node* p = ptrBins[idx]; // ptrBins[idx] is head ptr
ptrBins[idx] = ptrBins[idx]->next;
int x = p->value;
delete p;
return x;
}

void BinSort(int A[], int n){
int max = Max(A, n);

// Create bins array
Node** bins = new Node* [max + 1];

// Initialize bins array with nullptr
for (int i=0; i<max+1; i++){
bins[i] = nullptr;
}

// Update count array values based on A values
for (int i=0; i<n; i++){
Insert(bins, A[i]);
}

// Update A with sorted elements
int i = 0;
int j = 0;
while (i < max+1){
while (bins[i] != nullptr){
A[j++] = Delete(bins, i);
}
i++;
}

// Delete heap memory
delete [] bins;
}

int main() {

int A[] = {2, 5, 8, 12, 3, 6, 7, 10};
int n = sizeof(A)/sizeof(A[0]);

Print(A, n, "\t\tA");
BinSort(A, n);
Print(A, n, " Sorted A");
cout << endl;
return 0;
}

AltStyle によって変換されたページ (->オリジナル) /