0% found this document useful (0 votes)
7 views

Sort Algorithm-1

The document describes four sorting algorithms: bubble sort, insertion sort, selection sort, and quicksort. For each algorithm, it provides code snippets in C to implement the sorting logic and test it on sample integer arrays.

Uploaded by

thanhthailai3643
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Sort Algorithm-1

The document describes four sorting algorithms: bubble sort, insertion sort, selection sort, and quicksort. For each algorithm, it provides code snippets in C to implement the sorting logic and test it on sample integer arrays.

Uploaded by

thanhthailai3643
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

-- Bubble_sort --

#include <stdio.h>

void xuat(int A[], int N) {


for (int i = 0; i < N; i++) {
printf("%d ", A[i]);
}
printf("\n");
}

void Bubble_sort(int A[], int N) {


int j,temp;
bool sorted;
for(int i=0;i<N;i++){
j=N-1;
while(j>i){
if(A[j]<A[j-1]){
temp=A[j];
A[j]=A[j-1];
A[j-1]=temp;
sorted=true;
}
j--;
}
if(sorted==false){
break;
}
sorted=false;
xuat(A,5);
}
}

int main() {
int A[5] = {7, 2, 1, 9, 10};
Bubble_sort(A, 5);
return 0;
}

-- Insert-Sort --
#include <stdio.h>

void xuat(int A[], int N) {


for (int i = 0; i < N; i++) {
printf("%d ", A[i]);
}
printf("\n");
}

void insertion_sort(int A[], int N) {


int j,k;
for(int i=0;i<N;i++){
k=A[i+1];
j=i;
while(j>=0&&k<A[j]){
A[j+1]=A[j];
j--;
}
A[j+1]=k;
xuat(A,N);
}
}

int main() {
int A[5] = {2, 1, 4, 3, 5};
insertion_sort(A, 5);
return 0;
}

-- Selection_sort --

#include<stdio.h>
void xuat(int A[],int N){
for(int i=0;i<N;i++){
printf("%d ",A[i]);
}
printf("\n");
}
void selectionsort(int A[], int N){
int index, temp;
for(int i = 0; i < N; i++){
index=i;
for(int j = i+1; j < N; j++){
if(A[j] < A[index]){
index = j;
}
}
if(i != index){
temp = A[i];
A[i] = A[index];
A[index] = temp;
}
xuat(A,7);
}
}

int main(){
int A[7]={55,11,66,44,99,88,33};
selectionsort(A,7);
}

Advanced Short
-- Quick short --

#include<stdio.h>
void xuat(int A[],int N){
for(int i=0;i<N;i++){
printf("%d ",A[i]);
}
printf("\n");
}
void swap(int *A,int *B){
int temp=*A;
*A=*B;
*B=temp;
}
void check(int A[], int first, int last) {
if (first < last) {
int pivot = A[first];
int i = first + 1;
int j = last - 1;
while (i <= j) {
while (i <= j && A[i] <= pivot) {
i++;
}
while (i <= j && A[j] > pivot) {
j--;
}
if (i < j) {
swap(&A[j],&A[i]);
i++;
j--;
}
}
swap(&A[j],&A[first]);
check(A, first, j);
check(A, j + 1, last);
}
}

int main(){
int A[7]={55,11,66,44,99,88,33};
check(A,0,7);
xuat(A,7);
return 0;
}

You might also like