How to Use Bubble Sort in C Programming? - Simplilearn

文章推薦指數: 80 %
投票人數:10人

Bubble sort in C is a straightforward sorting algorithm that checks and swaps elements if they are not in the intended order. It compares two adjacent elements ... SoftwareDevelopmentDataScience&BusinessAnalyticsAI&MachineLearningProjectManagementCyberSecurityCloudComputingDevOpsBusinessandLeadershipQualityManagementSoftwareDevelopmentAgileandScrumITServiceandArchitectureDigitalMarketingBigDataCareerFast-trackEnterpriseOtherSegmentsArticlesEbooksFreePracticeTestsOn-demandWebinarsVideoTutorialsLiveWebinarsHomeResourcesSoftwareDevelopmentHowtoUseBubbleSortinCProgramming?Trendingnow20+TopMobileTestingInterviewQuestionsfor2022Article40+ImportantMainframeInterviewQuestionsandAnswersArticleBlockchainCareerGuide:AComprehensivePlaybookToBecomingABlockchainDeveloperEbookA*Algorithm:AnIntroductionToThePowerfulSearchAlgorithmArticleSplitInPythonArticleWhatisJavaAPIandTheNeedforJavaAPIs?VideoTutorialBestProgrammingLanguagestoLearnin2022ArticleListtoStringinPythonArticleHowtoCrackaTop-TierSoftwareDevelopmentInterviewWebinarAngularJSVs.Angular2Vs.Angular4:UnderstandingtheDifferencesArticleHowtoUseBubbleSortinCProgramming?BySimplilearnLastupdatedonJul13,2022126499TableofContentsViewMore Theremightcomesituationswhenyouwouldwanttoorderdatainaspecificorder.That’swhenasortingalgorithmwillcomeinhandy.BubblesortinCisastraightforwardsortingalgorithmthatchecksandswapselementsiftheyarenotintheintendedorder.Itcomparestwoadjacentelementstofindwhichoneisgreaterorlesserandswitchesthembasedonthegivenconditionuntilthefinalplaceoftheelementisfound.Inthisarticle,youwilllearnaboutbubblesortandhowtowriteaCprogramforbubblesortimplementationusingdifferentways. PostGraduateProgram:FullStackWebDevelopmentinCollaborationwithCaltechCTMEEnrollNow TheBubbleSortAlgorithminC Thebasicbubblesortalgorithmcanbeexplainedasfollows: bubbleSort(array)   forirightElement       swapleftElementandrightElement endbubbleSort Thisalgorithmdoestheswappingofelementstogetthefinaloutputinthedesiredorder.Forinstance,ifyoupassanarrayconsistingoftheelements:(6,3,8,2,5,7),thefinalarrayafterthebubblesortimplementationwillbe:(2,3,5,6,7,8). HowDoestheCProgramforBubbleSortWork? Asmentioned,theCprogramforbubblesortworksbycomparingandswappingadjacentelementsinanarray.Let’sunderstandthisinastep-by-stepmethod: Supposewewanttosortanarray,let’snameitarr,withnelementsinascendingorder;thisishowthebubblesortalgorithmwillwork. Startsfromthefirstindex:arr[0]andcomparesthefirstandsecondelement:arr[0]andarr[1] Ifarr[0]isgreaterthanarr[1],theyareswapped Similarly,ifarr[1]isgreaterthanarr[2],theyareswapped Theaboveprocesscontinuesuntilthelastelementarr[n-1] Allfourstepsarerepeatedforeachiteration.Uponcompletingeachiteration,thelargestunsortedelementismovedtotheendofthearray.Finally,theprogramendswhennoelementsrequireswapping,givingusthearrayinascendingorder.Nowthatweknowtheworkingofthebubblesortlet’simplementitinCprogrammingusingdifferentmethods. CProgramforBubbleSortUsingforLoop WewillwritethefirstCprogramforbubblesortusingaforloop.Inthisexample,wewillausenestedforloopinCtosorttheelementsofaone-dimensionalarray.Tobeginwith,wewillaskforthetotalnumberofelementsandthenthevaluesfromtheuser.Oncewegettheelements,wewillusetheforlooptoiteratethroughtheelementsandsorttheminascendingorder. #include intmain(){     intarr[50],num,x,y,temp;         printf("PleaseEntertheNumberofElementsyouwantinthearray:");     scanf("%d",&num);         printf("PleaseEntertheValueofElements:");     for(x=0;xarr[y+1]){                         temp=arr[y];                 arr[y]=arr[y+1];                 arr[y+1]=temp;             }         }     }     printf("Arrayafterimplementingbubblesort:");     for(x=0;x intmain(){     intarr[50],num,x,y,temp;       printf("PleaseEntertheNumberofElementsyouwantinthearray:");     scanf("%d",&num);       printf("PleaseEntertheValueofElements:");     for(x=0;xarr[y+1]){                 temp=arr[y];                 arr[y]=arr[y+1];                 arr[y+1]=temp;             }             y++;         }             x++;     }       printf("Arrayafterimplementingbubblesort:");     for(x=0;x voidbubbleSortExample(intarr[],intnum){     intx,y,temp;       for(x=0;xarr[y+1]){                 temp=arr[y];                 arr[y]=arr[y+1];                 arr[y+1]=temp;             }         }     } } intmain(){     intarr[50],n,x;       printf("PleaseEntertheNumberofElementsyouwantinthearray:");     scanf("%d",&n);         printf("PleaseEntertheValueofElements:");     for(x=0;x voidSwapFunc(int*i,int*j){     intTemp;     Temp=*i;     *i=*j;     *j=Temp; } voidbubbleSortExample(intarr[],intnum){     intx,y,temp;       for(x=0;xarr[y+1]){                 SwapFunc(&arr[y],&arr[y+1]);             }         }     } } intmain(){     intarr[50],n,x;       printf("PleaseEntertheNumberofElementsyouwantinthearray:");     scanf("%d",&n);         printf("PleaseEntertheValueofElements:");     for(x=0;x //Functionforbubblesorting voidbubbleSortExample(intarr[],intn){     for(inti=0;iarr[x+1]){                 inttemp=arr[x];                 arr[x]=arr[x+1];                 arr[x+1]=temp;                     Swap=1;             }         }             if(Swap==0){//Noswappingrequired             break;         }         } } voiddisplayArray(intarr[],intn){         for(intx=0;x



請為這篇文章評分?