Created
July 28, 2018 11:36
-
-
Save summer-wu/400f93d39531ce92335f737b27b71a8d to your computer and use it in GitHub Desktop.
两种bubble_sort。bubble_Me是我写的,可以排序,但具体步骤和冒泡不同。bubble_online是网上找的
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.m | |
// bubble | |
// | |
// Created by n on 28/07/2018. | |
// Copyright © 2018 summerwuOrganization. All rights reserved. | |
// | |
#include <stdio.h> | |
#include <stdlib.h> | |
void swap(int *a,int j,int i){ | |
int t = a[j]; | |
a[j]=a[i]; | |
a[i]=t; | |
} | |
void printArray(int *a,int len){ | |
for (int i=0; i<len; i++) { | |
printf("%d ",a[i]); | |
} | |
printf("\n"); | |
} | |
int * randomArray(int len){ | |
#define random(min,max) ((arc4random() % (max-min+1)) + min) | |
int *a=malloc(sizeof(int)*len); | |
for (int i=0; i<len; i++) { | |
a[i]=(int)random(0,10); | |
} | |
return a; | |
} | |
void bubble_Me(int *a,int len){ | |
for (int i=0; i<len; i++) { | |
for (int j=0; j<i; j++) { | |
if (a[j]>a[i]) { | |
swap(a,j,i); | |
} | |
} | |
} | |
} | |
// A function to implement bubble sort | |
//from https://www.geeksforgeeks.org/bubble-sort/ | |
void bubble_online(int arr[], int n) | |
{ | |
int i, j; | |
for (i = 0; i < n-1; i++) | |
// Last i elements are already in place | |
for (j = 0; j < n-i-1; j++) | |
// printf(@"i=%d j=%d\n",i,j); | |
if (arr[j] > arr[j+1]) | |
swap(arr,j,j+1); | |
} | |
int main(int argc, const char * argv[]) { | |
int len = 10; | |
int *a = randomArray(len); | |
printArray(a, len); | |
// bubble_online(a,len); | |
bubble_Me(a, len); | |
printArray(a, len); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment